考虑到扩展 Canvas 的 Display 类,我遇到了一个问题。 单个线程在同一个类中运行。 在这个线程中,重绘方法被调用。 然而,虽然线程工作正常,但从未调用 paint 方法!
这是我的代码(我省略了所有不相关的内容):
package display;
public final class Display extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
private Frame frame;
private GraphicsEnvironment ge;
private GraphicsDevice gd;
public BDisplay() {
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gd = ge.getDefaultScreenDevice();
frame = new Frame();
//frame.setUndecorated(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
frame.add(this);
frame.setLayout(null);
//gd.setFullScreenWindow(frame);
}
@Override
public final void paint(Graphics g) {
//THIS METHOD IS NEVER CALLED
System.out.println("Paint method was called!");
super.paint(g);
//...
}
@Override
public synchronized void run() {
while (isRunning()) {
//THIS LOOP WORKS FINE.
this.repaint();
}
}
}
与isRunning()等缺失函数无关。 它们存在,我只是将它们排除在外。
我以前从来没有遇到过这样的问题, 尽管我已经有一段时间没有使用 SWING 或 AWT 做过任何事情了。
有人能帮忙吗?
线程循环工作正常, 但是重绘似乎没有按计划进行......
最佳答案
在添加组件(即 Canvas
和之前的 JPanel
)之前,您将实现 JFrame
.
试试这个
public BDisplay() {
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gd = ge.getDefaultScreenDevice();
frame = new Frame();
frame.setResizable(false);
frame.add(this);
//frame.setLayout(null); // Why are you using a null layout?
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
编辑
顺便说一句,我建议使用 JPanel
而不是 Canvas
,因为不建议您混合使用重型组件和轻型组件。有关详细信息,请参阅 Mixing heavy and light components .
关于java - 为什么我的重绘不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6678065/