简体   繁体   English

如何刷新嵌套在另一个Jpanel中的JPanel?

[英]How to refresh a JPanel that is nested inside another Jpanel?

I have nested a Jpanel within another JPanel. 我在另一个JPanel中嵌套了一个Jpanel。 I want to refresh one of JPanels while not refreshing the other one. 我想刷新一个JPanels,而不刷新另一个。 I have the following code, I can use the repaint() function however it will update all of the JPanels not just the one that I want (the Time JPanel). 我有以下代码,我可以使用repaint()函数,但是它将更新所有的JPanels,而不仅仅是我想要的一个(Time JPanel)。

How would I go about refreshing just the Time JPanel? 我将如何仅刷新Time JPanel? Leaving the Weather JPanel untouched? 保持天气JPanel不变? I would like to be able to do this from an external thread. 我希望能够从外部线程执行此操作。

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
}
}

Your code is completely wrong. 您的代码是完全错误的。 The paintComponent() method is used for painting with the Graphics object. paintComponent()方法用于与Graphics对象一起绘画。 You should NEVER add components to a panel or change the size, or change the location of a component in a painting method. 绝对不要在面板上添加组件,更改尺寸或更改绘画方法中组件的位置。

There is no need for you to override the paintComponent() method. 您无需重写paintComponent()方法。

In the constructor of your class is where you create the child panels and add them to the main panel. 在类的构造函数中,您可以在其中创建子面板并将其添加到主面板。 Something like: 就像是:

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);
    }
}

Notice how I also changed your variables: 请注意,我还如何更改您的变量:

  1. you should not be using static 你不应该使用静态
  2. variable names start with a lower case character. 变量名以小写字母开头。

I suggest you start by reading the Swing Tutorial for Swing basics. 我建议您先阅读Swing教程,了解Swing的基础知识。 You can check out the section on How To Use Panels for a working example. 您可以查看有关How To Use Panels的部分的工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM