简体   繁体   中英

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

I have nested a Jpanel within another JPanel. I want to refresh one of JPanels while not refreshing the other one. 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).

How would I go about refreshing just the Time JPanel? Leaving the Weather JPanel untouched? 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. 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.

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. You can check out the section on How To Use Panels for a working example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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