java - 在单独的类中重新绘制/更新 JPanel 时出现问题

标签 java swing jframe jpanel

我正在处理 Java 作业,并且创建了一个 JFrame 小程序,该小程序具有在单独的类中创建的四个面板,这些面板返回到主类并添加到主面板。 我面临的问题是我的南面板中有一个组合框。根据该组合框中的选择,我希望根据该选择更新一个或多个其他面板。我不知道如何实现这一点,我已经考虑重新绘制单个面板,甚至重新创建整个主面板。 任何帮助和/或建议将不胜感激。

我已经从主面板类中发布了下面的代码,以供初学者使用。

我是第一次在这里发帖,所以如果没有足够的细节或者我遗漏了一些内容,请告诉我。

public class Main_GUI_Panel extends JFrame {

    public static Panel_North northPanel;
    public static Panel_Center centerPanel;
    public static Panel_West westPanel;
    public static Panel_South southPanel;
    private int index = -1;

    public Main_GUI_Panel() {
        super("Java 2: Final Project");
        getContentPane().setBackground(Color.BLACK); //set the applet background color
        setLayout(new BorderLayout());  //set the Layout for the applet

        //START - call methods to create & set panels
            northPanel = new Panel_North();
            westPanel = new Panel_West();
            centerPanel = new Panel_Center();
            southPanel = new Panel_South();

            add(northPanel.setNorth(),BorderLayout.NORTH); //set the North portion of the applet
            add(westPanel.setWest(index),BorderLayout.WEST); //set the West portion of the applet
            add(centerPanel.setCenter(),BorderLayout.CENTER); //set the Center portion of the applet
            add(southPanel.setSouth(),BorderLayout.SOUTH); //set the South portion of the applet
        //END - call methods to set panels
    }

最佳答案

当您创建 GUI 时,您应该(必须)创建一个或多个模型类来保存 GUI 的数据。这是模型。你的 GUI 组件就是 View 。这些部分构成了应用程序的模型/ View / Controller (MVC)。

您将顶级模型类的实例传递给 GUI 的所有面板。每个面板都可以更新模型类,反过来,面板从模型中获取数据。

因此,您在一个面板中执行的操作会影响不同面板的显示。

This answer详细介绍 GUI 模型和 GUI View 。

关于java - 在单独的类中重新绘制/更新 JPanel 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13823198/

相关文章:

java - 如何使包含 Jpanel 的 Jframe 可滚动?

java - Google 分析事件显示在实时 View 中,但未存档

java - Libgdx 窗口调整大小 : Keeping Aspect Ratio

java - JTabbedPane 正在读取击键并切换选项卡

java - 获取组件的最后一次调整大小事件

java - 如何在别处绘制不可见的 JFrame?

java - 如何为 jframe 设置标题?

java - 从servlet发送数据到jsp

java - 关于maven中的依赖

java - 一个类的 JButton 如何将文本附加到另一类的 JTextArea