嘿,我正在编写一个程序,出于调试目的,我试图让程序截取部分显示的屏幕截图。我想更新显示器,但我似乎无法让它工作。我确信这是一个简单的问题,但我对 Java Applet 的经验非常少。
这是我遇到问题的部分:
...
Thread.sleep(5000);
try {gb = new GameBoard(frame.getBounds());}
catch(Exception e){System.out.println("Error.");} // Make "gameboard" Object
while (true)
{
Thread.sleep(1000);
gb.grabImage(); // use java.awt.Robot's createScreenCapture()
ImageIcon icon = new ImageIcon(gb.image()); // wrap the image
JLabel label = new JLabel(icon, JLabel.CENTER);
frame.getContentPane().add(label,BorderLayout.EAST); //display the image (works)
//JOptionPane.showMessageDialog(null, label, "icon", -1);
label.repaint(); //update the display??
frame.repaint();
frame.getContentPane().repaint();
}
正如我所说,图像会出现,并且如果我更改 Applet 大小,将会创建新的图像,但我需要一个不断变化的图像。
提前致谢!
最佳答案
您每次通过循环都会创建并添加一个新的JLabel
。由于您要更改组件树的结构,因此需要在框架的内容 Pane 上调用revalidate
。
更好的解决方案是仅更改单个 JLabel 上的图像。创建一个标签,添加它,然后在循环中使用 JLabel.setIcon
和 repaint
。
关于java - 无法让 JFrame 刷新图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4581607/