Reputation: 127
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
}
}
Upvotes: 0
Views: 429
Reputation: 324157
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:
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.
Upvotes: 2