我是 Swing 新手。我想编写一个程序来读取文件并根据从文件中读取的数据绘制一些内容。
我查了教程,他们在paint()中调用了绘图方法。因此,我也在 Paint() 方法中添加了读取文件的代码。但是,我注意到 Paint() 方法可能会被多次调用。因此每次调用paint()方法时都会读取该文件。
我只想读取该文件一次。如果我在 main() 方法中读取文件,如何访问 Graphics 对象?或者有其他方法可以解决这个问题吗?
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);
}
}
最佳答案
I checked the tutorials and they call the drawing methods in paint().
这可能是一个旧的 AWT 教程。这不是 Swing 中绘画的方式。使用 Swing 时,您应该重写 PaintComponent(...) 方法。阅读 Swing 教程中关于 Custom Painting 的部分获取示例和更多信息。
However, I noticed that the paint() method may be called multiple times
Swing 将确定组件何时需要重新绘制并调用绘制方法。
I want to read the file only once
绘画应该尽可能高效。因此,将代码添加到类的构造函数中以读取文件。
关于java - 如何在Java Swing中只读取一次数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3329741/