Hi, I'm new to Java and I just can't find out how to do this properly.
I have a main class that hold the frame and paints, a class for drawing my game, and an image that is drawn too.
I want to count the amount of times I click on this "android" (right now it counts if i click the screen) but the text from the class Game doesn't update.
And I don't understand why
doesn't work. In my head the image should be inside the borders but it isn't. Have I calculated the pixels wrong or am I missing something?androidX = Main.width - android.getWidth();
public class Main extends JPanel{ public static final int width = 600; public static final int height = 600; Game game = new Game(); Android android = new Android(); public void paint(Graphics g) { super.paint(g); game.render(g); android.render(g); } public Main() { addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { System.out.println("Hit: " + android.getTimesHit()); // This works android.mousePressed(e); } public void mouseReleased(MouseEvent e) { } }); setFocusable(true); } public static void main(String[] args) throws InterruptedException { Main main = new Main(); JFrame frame = new JFrame("Main"); frame.add(main); frame.setSize(width, height); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setResizable(false); while (true) { main.repaint(); Thread.sleep(10); } } }
public class Game { Android android = new Android(); public void render (Graphics g) { Font fnt0 = new Font("arial", Font.BOLD, 10); g.setFont(fnt0); g.setColor(Color.BLACK); g.drawString("Hit: " + android.getTimesHit(), 50, 70); // This doesn't work, it always says zero } }
public class Android { public static BufferedImage android; private int timesHit = 0; private int androidX = 0; private int androidY = 0; public int getTimesHit() { return timesHit; } public void setTimesHit(int timesHit) { this.timesHit = timesHit; } public Android() { try { android = ImageIO.read(getClass().getResource("android.png")); } catch (IOException e) { e.printStackTrace(); } } public void mousePressed(MouseEvent e) { move(); } void move() { androidX = Main.width - android.getWidth(); androidY = Main.height - android.getHeight(); //The image gets outside the borders, what is wrong? setTimesHit(getTimesHit() + 1); } public void render(Graphics g) { g.drawImage(android, androidX, androidY, null); } }