【发布时间】:2018-03-28 19:43:08
【问题描述】:
下面的代码是一个涉及图像的非常简单的测试。 每当我向 System.in 发送“a”时它应该重新绘制图像,并且每当我发送“q”时它应该退出程序。
问题是只有出口有效: 永远不会调用paint() 方法,我不知道为什么。
我检查了对“super.paint()”的调用,尝试用paintCompoenent(Graphics g) 替换paint(Graphics g),但似乎没有任何效果:根本没有调用。
问题是否涉及 main() 中的 Scanner?
程序中的路径和我用的不一样,而且第一次绘制是对的,所以应该没有问题。
注意,如果有用的话,我正在使用 Eclipse Oxygen 和 Java9 SE
谢谢大家!
代码粘贴:
public class TestImagePanel extends JPanel {
private BufferedImage image;
private int xpos = 0;
private int ypos = 0;
private String _imagePath = "//myFolder//image.png";
public TestImagePanel() {
try {
image = ImageIO.read(new File(_imagePath));
} catch (IOException ex) {}
}
public void paint(Graphics g) {
super.paint(g);
System.out.println("painting LOG");
g.drawImage(image, this.xpos++, this.ypos++, this);
}
public void update(String a) {
System.out.print("Receiving:" + a + "---" + xpos + ":" + ypos);
if (a.equals("a"))
repaint();
else if (a.equals("q")) {
System.out.println("LOGOUT");
System.exit(0);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("test");
TestImagePanel testimg = new TestImagePanel();
frame.add(new TestImagePanel());
frame.setSize(new Dimension(600, 600));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Scanner in = new Scanner(System.in);
while (true)
testimg.update( in .next());
}
}
【问题讨论】:
-
我刚刚测试了您的代码,没有任何问题。你期望发生的事情没有发生?从你的问题看不清楚。
repaint()方法被调用,它什么也不做,因为没有什么可做的。 -
您还调用了两次
new TestImagePanel()- 一次将其分配给testimg,然后将另一个添加到frame -
我希望在新的 xpos 和 ypos 上重新绘制图像,他们应该得到一个 ++
-
另外,请参阅this question - 你是
tying up your GUI's event thread for console input- 不要使用扫描仪为你的 GUI 应用程序输入。您应该关注的关键信息是 swing 的“事件调度线程”的概念 - 值得一读的是 this question -
“我希望在新的 xpos 和 ypos 上重新绘制图像,它们应该得到一个 ++” - 您正在更新
testimg的一个实例,它是不在屏幕上