我正在制作一个程序,它有一个可以滚动的图像,如果按下按钮,我不知道如何更新图像(例如:向图像添加绿色椭圆。)它已经绘制了图像进入 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();
}
}