问题描述
我有一个继承自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.
任何想法?代码如下。
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();
}
推荐答案
尝试拨打 somePanel.revalidate()
。这将告诉AWT您已更改组件树。
Try calling somePanel.revalidate()
. That will tell the AWT that you have changed the component tree.
编辑:从更改
更改为 revalidate
这篇关于如何在绘制之后重新绘制JPanel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!