Nick Haughton
Nick Haughton

Reputation: 99

JFrame not updating graphics from a separate class

I am running into a strange problem I cannot solve. I have two classes a JFrame class:

public class TowerDefenceFrame extends JFrame {

public TowerDefenceFrame() {
    super("Tower Defence");
    setSize(1023, 708);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    //setResizable(false);
}

public static void main(String[] args) {

    TowerDefenceFrame tdf = new TowerDefenceFrame();
    tdf.setVisible(true);
    Map.main(args);
  }
}

and a graphics class:

public class Board extends JPanel implements ActionListener {
BufferedImage road;
BufferedImage grass;
Timer time;

public Board() {
    setFocusable(true);
    time = new Timer(5, this);
    time.start();

    try {
        road = ImageIO.read(new File("../road.png"));
        grass = ImageIO.read(new File("../grass.png"));
    } catch (IOException ex) {
        Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
    }


}

public void actionPerformed(ActionEvent e) {
    repaint();

}

public void paint(Graphics g) {
     super.paint(g);

        for (int i = 0; i <= Map.mapWidth - 1; i++) {
            for (int l = 0; l <= Map.mapHeight - 1; l++) {

            if (Map.mapArray[l][i] == 1) {
                g.drawImage(road, (Map.blockSize * i), (Map.blockSize * l), this);

            } else if (Map.mapArray[l][i] == 0) {
                g.drawImage(grass,(Map.blockSize * i), (Map.blockSize * l), this);
            } 

        }





    }
         repaint();

   }
}

When I run the application the JFrame appears, however the graphics from the Board class do not. I was looking for answers to this problem and couldn't find one. I noticed that when I resized the JFrame the images from the board class appeared. This led me to believe that I had to update the board class to get the graphics. I tried adding a timer loop in my JFrame class to add the Board class every 1/2 second. It didn't work. I have been stumped on this problem for a while and I'm wondering if any of you could help out,

Thanks.

Upvotes: 2

Views: 846

Answers (1)

syb0rg
syb0rg

Reputation: 8247

Classes that start with J such as JApplet and JFrame are Swing, and Applet and Frame are AWT. The method paint() is used with the AWT class, yet you are using JPanels and JFrames.

Also, because you call super in your paint() method (which you will change to paintComponent), you have to @Override for it to work properly.

Upvotes: 2

Related Questions