如何在 JPanel 上绘制后重新绘制它?
我有一个继承自 JPanel 的组件,我在上面绘制了一个网格。现在我有一个 JComboBox,我希望用户能够在此处选择网格大小,然后按下按钮来更改网格(重新绘制网格)。
问题是它绘制了初始网格,但是一旦用户从 JComboBox 选择网格大小并单击按钮,就不会发生任何事情。我必须最小化表单,然后再次恢复它才能看到更改。
有什么想法吗?代码如下。
组件:
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();
}
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).
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.
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试调用
somePanel.revalidate()
。这将告诉 AWT 您已经更改了组件树。编辑:从
invalidate
更改为revalidate
Try calling
somePanel.revalidate()
. That will tell the AWT that you have changed the component tree.EDIT: Changed from
invalidate
torevalidate