簡體   English   中英

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

[英]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);
    }
}

請注意,我還如何更改您的變量:

  1. 你不應該使用靜態
  2. 變量名以小寫字母開頭。

我建議您先閱讀Swing教程,了解Swing的基礎知識。 您可以查看有關How To Use Panels的部分的工作示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM