[英]How to refresh a JPanel that is nested inside another Jpanel?
我在另一个JPanel中嵌套了一个Jpanel。 我想刷新一个JPanels,而不刷新另一个。 我有以下代码,我可以使用repaint()函数,但是它将更新所有的JPanels,而不仅仅是我想要的一个(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
}
}
您的代码是完全错误的。 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);
}
}
请注意,我还如何更改您的变量:
我建议您先阅读Swing教程,了解Swing的基础知识。 您可以查看有关How To Use Panels
的部分的工作示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.