Java 在 JPanel 上绘制后如何重新绘制它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4392722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to repaint a JPanel after have drawn on it?
提问by Aerozeek
I have a component that inherits from JPanel, I draw a grid on it. Now I have a JComboBox and I want the user to be able to choose the grid size here and then press a button to make the grid change (repaint the grid).
我有一个从 JPanel 继承的组件,我在它上面画了一个网格。现在我有一个 JComboBox,我希望用户能够在这里选择网格大小,然后按下一个按钮来改变网格(重新绘制网格)。
The thing is that it paints the initial grid, but once the user choses a grid size from the JComboBox and clicks the button, nothing happens. I have to minimize the form and then restore it again to see the changes.
问题是它绘制了初始网格,但是一旦用户从 JComboBox 中选择了一个网格大小并单击了按钮,就没有任何反应。我必须最小化表单,然后再次恢复它以查看更改。
Any Ideas? The Code is below.
有任何想法吗?代码如下。
The Component:
组件:
public class Board extends JPanel {
...
protected void paintComponent(Graphics og) {
super.paintComponent(og);
...
}
}
}
Main Class
主类
public class Main extends javax.swing.JFrame {
...
public Main() { //This works great.
board = new Board( ... );
somePanel.add(board, BorderLayout.CENTER);
}
public void someButtonActionPerformed(Event e) { //This is not working
somePanel.remove(board);
board = new Board( ... );
somePanel.add(board);
somePanel.invalidate()
board.repaint();
}
采纳答案by Cameron Skinner
Try calling somePanel.revalidate()
. That will tell the AWT that you have changed the component tree.
尝试调用somePanel.revalidate()
。这将告诉 AWT 您已经更改了组件树。
EDIT: Changed from invalidate
to revalidate
编辑:更改invalidate
为revalidate