如何在 JPanel 上绘制后重新绘制它?

发布于 2024-10-06 21:30:43 字数 848 浏览 2 评论 0原文

我有一个继承自 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡墨 2024-10-13 21:30:43

尝试调用 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 to revalidate

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文