【问题标题】:How to refresh a JPanel that is nested inside another Jpanel?如何刷新嵌套在另一个 Jpanel 中的 JPanel?
【发布时间】:2017-03-11 16:52:10
【问题描述】:

我在另一个 JPanel 中嵌套了一个 Jpanel。我想刷新其中一个 JPanel,而不刷新另一个。我有以下代码,我可以使用 repaint() 函数,但是它会更新所有的 JPanel,而不仅仅是我想要的(Time JPanel)。

我将如何只刷新 Time JPanel?保持天气 JPanel 不变? 我希望能够从外部线程执行此操作。

public class MainPanel extends JPanel{

public static JPanel TimePanel = new Time();
public static Weather WeatherPanel = new Weather();

public void paintComponent(Graphics g){
    super.paintComponent(g);
    this.setBackground(Color.BLACK);
    this.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));

    TimePanel.setLocation(0, 0);
    TimePanel.setSize(new Dimension(500, 300));
    this.add(TimePanel);

    WeatherPanel.setLocation(0,300);
    WeatherPanel.setSize(new Dimension(100, 100));
    this.add(WeatherPanel);

    //repaint();//Just causes recursion
}
}

【问题讨论】:

    标签: java swing jpanel refresh repaint


    【解决方案1】:

    您的代码完全错误。 paintComponent() 方法用于使用 Graphics 对象进行绘画。切勿将组件添加到面板或更改大小,或在绘画方法中更改组件的位置。

    您无需重写paintComponent() 方法。

    在类的构造函数中,您可以创建子面板并将它们添加到主面板。比如:

    public class MainPanel extends JPanel
    {
    
        public JPanel timePanel = new Time();
        public Weather teatherPanel = new Weather();
    
        public MainPanel()
        {
            this.setBackground(Color.BLACK);
            this.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
    
            this.add(timePanel);
            this.add(weatherPanel);
        }
    }
    

    注意我是如何改变你的变量的:

    1. 你不应该使用静态的
    2. 变量名称以小写字符开头。

    我建议您首先阅读 Swing Tutorial 了解 Swing 基础知识。您可以查看How To Use Panels 上的部分以获取工作示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多