问题描述
我有一个继承自 JPanel 的组件,我在其上绘制了一个网格.现在我有一个 JComboBox,我希望用户能够在这里选择网格大小,然后按下一个按钮来改变网格(重新绘制网格).
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).
问题是它绘制了初始网格,但是一旦用户从 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.
有什么想法吗?代码如下.
Any Ideas? The Code is below.
public class Board extends JPanel {
...
protected void paintComponent(Graphics og) {
super.paintComponent(og);
...
}
}
}
主类
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();
}
推荐答案
尝试调用 somePanel.revalidate()
.这将告诉 AWT 您已经更改了组件树.
Try calling somePanel.revalidate()
. That will tell the AWT that you have changed the component tree.
从 invalidate
更改为 revalidate
这篇关于在 JPanel 上绘制后如何重新绘制它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!