I am new to Swing. I want to write a program which reads a file and draws something depending on the data read from the file.
I checked the tutorials and they call the drawing methods in paint(). So I added the code to read the file too in the paint() method. However, I noticed that the paint() method may be called multiple times. So the file would be read each time the paint() method is called.
I want to read the file only once. If I read the file in main() method how do I get access to the Graphics object? Or is there any other approach to solve this problem?
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JPanel {
public void paint(Graphics g) {
// Code to read a file
// Code to draw something depending on the data read from the file
}
public static void main(String[] args) {
JFrame frame = new JFrame("Java 2D Skeleton");
frame.add(new Test());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
That may be an old AWT tutorial. That is NOT the way painting is done in Swing. When using Swing you should be overriding the paintComponent(…) method. Read the section from the Swing tutorial on Custom Painting for an example and more information.
Swing will determine when a component needs to be repainted and invoke the painting methods.
Painting should be as efficient as possible. So add the code to the constructor of your class to read the file.