我正在制作一个程序,其中有一张您可以在其上滚动的图像,但我无法弄清楚如果按下按钮如何更新图像(例如:向图像添加一个绿色椭圆。)它已经将图像绘制到 JScrollPane 中,您可以四处滚动,但是当您单击按钮时,它不会刷新图像。 (更多细节在代码中) 这是代码:
public class PegMaster extends JPanel implements ActionListener {
//Note: not complete code
public PegBox[] pegbox = new PegBox[9];
public static Dimension size = new Dimension(520, 500);
public BufferedImage canvas;
public Graphics2D g2d;
public JScrollPane scroller;
JPanel panel;
private Canvas window;
JScrollPane pictureScrollPane;
public PegMaster() {
JButton button = new JButton("test");
button.addActionListener(this);
add(button);
canvas = new BufferedImage((int)size.getWidth()-30, 75 * GUESSES, BufferedImage.TYPE_INT_RGB);
g2d = canvas.createGraphics();
for(int i = 0;i<=pegbox.length-1;i++) {
pegbox[i] = new PegBox(i, g2d);
}
window = new Canvas(new ImageIcon(toImage(canvas)), 1);
//Class Canvas is a Scrollable JLabel to draw to (the image)
pictureScrollPane = new JScrollPane(window);
pictureScrollPane.setPreferredSize(new Dimension((int)size.getWidth()-10, (int)size.getHeight()-20));
pictureScrollPane.setViewportBorder(BorderFactory.createLineBorder(Color.black));
add(pictureScrollPane);
//adds the scrollpane, but can't update the image in it
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
//just adds the scrollpane
}
});
}
public void paint(Graphics g) {
super.paint(g);
for(int i = 0;i<=pegbox.length-1;i++) {
//pegbox[i] = new PegBox(i);
pegbox[i].draw(g2d);
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
//tried re-making the scrollpane, didn't work.
//window = new Canvas(new ImageIcon(toImage(canvas)), 1);
//pictureScrollPane = new JScrollPane(window);
//pictureScrollPane.setPreferredSize(new Dimension((int)size.getWidth()-10 (int)size.getHeight()-20));
//pictureScrollPane.setViewportBorder(BorderFactory.createLineBorder(Color.black));
//tried imageupdate: pictureScrollPane.imageUpdate(canvas, 0, 0, 0 (int)size.getWidth()-10, (int)size.getHeight()-20);
//remove(pictureScrollPane);
//tried this: pictureScrollPane.revalidate();
repaint();
}
}
最佳答案
首先,不要使用 Canvas
它是一个重量级的组件,从长远来看它只会给你带来问题,使用 JComponent
或 JPanel
其次,不要覆盖paint
,而是使用paintComponent
。 paint
做了很多工作,包括绘制边框和子组件之类的东西。如果您使用 paintComponent
会更好,因为它位于您想要执行的绘制层次结构中的正确层。
第三,永远不要在事件调度线程中调用类似Thread.sleep
的东西。这将导致事件队列暂停并停止响应事件,使您的程序看起来像是停滞了。
第四,切勿在绘制方法中调用repaint
(invalidate
、revalidate
或任何可能导致重绘请求发生的方法)。您最终只会用尽 CPU,并被迫终止该进程。
第五,您没有提供actionPerformed
方法,这可能是所有操作(和问题)所在的地方。我想你需要调用 window.repaint()
和可能的 window.invalidate()
(以相反的顺序),但因为你没有提供使用这个代码,那只是猜测......
关于Java JScrollPane 更新图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12433235/