Spe*_*r H 1 java swing image paint jscrollpane
我正在制作一个具有滚动图像的程序,如果按下按钮,我无法弄清楚如何更新图像(例如:向图像添加绿色椭圆.)它已经绘制了将图像放入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();
}
}
Run Code Online (Sandbox Code Playgroud)
首先,不要使用Canvas
它是一个重量级的组件,它只会导致你长期问题,使用JComponent
或JPanel
其次,不要覆盖paint
,paintComponent
改用. paint
做了很多工作,包括绘制边框和子组件之类的东西.如果您paintComponent
在绘图层次结构中的右侧层使用它,那么它会更好.
第三,永远不要Thread.sleep
在Event Dispatching Thread中调用类似的东西.这将导致事件队列暂停并停止响应事件,使您的程序看起来像是停滞不前.
第四,NEVER调用repaint
(invalidate
,revalidate
或可能导致发生一个重画请求的任何方法)的涂料方法内.你最终会最终耗尽你的CPU,你将被迫杀死这个过程.
第五,你没有提供actionPerformed
方法,这可能是所有行动(和问题)的所在.我想你需要调用window.repaint()
并且可能window.invalidate()
(以相反的顺序),但由于你没有提供使用这个代码,这只是猜测......