2010-09-05 66 views
0

我有從JPanel擴展的類。這個類包含幾個其他的JComponents和大量的繪畫。我做了什麼,而且我知道這是不正確的,因爲我爲畫作壓倒了paintComponent,所以這麼好。哪裏可以設置子組件的大小

但是我也在這個方法中設置了所有子組件的位置和大小,因爲它們依賴於JPanel的getWidth和getHeight。我知道這不是組件的地方,但我在哪裏做這種東西。在建設者時間尺寸沒有設置。那麼它如何糾正?因爲只要我在paintComponent方法中有位置和大小的方法,CPU就不會停止計算某些東西。

編輯:我看起來是這樣的;

public class abc extends JPanel { 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 

     /** all the painting stuff */ 
     textfield.setLocation(
      this.getWidth() * someValue, 
      this.getHeight() * someotherValue); 
     // also depends on getHeight() and getWidth() 
     textfield.setSize(new Dimension(getHeight(), getWidth()); 
    } 
}  

一切工作正常,除了我總是有​​10%左右的CPU使用率。如果兩條線都被佔用,則CPU使用率降至0%。所以現在我使用了像你推薦的Layoutmanager。而且仍然一切看起來很好,但CPU負載並沒有改變,它仍然保持在10%左右。該代碼,它現在的樣子:

public class abc extends JPanel { 

    public abc() { 
     GridBagLayout gblayout = new GridBagLayout(); 

     this.setLayout(gblayout); 

     textfield = new JTextField(); 
     textfield.setHorizontalAlignment(JTextField.CENTER); 
     textfield.setBackground(new Color(0, 0, 0, 0)); 
     textfield.setBorder(null); 
     textfield.setText("0"); 

     gblayout.setConstraints(textfield, new GridBagConstraints(
      0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, 
      GridBagConstraints.BOTH, new Insets(4, 4, 4, 4), 1, 1)); 

     this.add(textfield); 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     /** still the same paintings */ } 
} 
+0

重新格式化的代碼;如果不正確請回復。 – trashgod 2010-09-06 17:16:39

回答

1

這將真正幫助,如果你向我們展示一些代碼,也許說明你正在嘗試做的,但據我瞭解,你試圖做一個太多JPanel的。你應該有一個獨立的面板,如果你打算在它上面繪製,則會覆蓋paintComponent(),而另一個(或多個)面板用於容納你的其他組件。

事實上,調整個別組件幾乎是不可能的,因爲它們必須遵守爲其父組件選擇的佈局(通常是JPanel),因此您必須牢記這一點。

1

組件的大小和位置由佈局管理器設置。初始化框架後,會調用pack()來調整所有組件的大小。

您應該首先設置最小值,最大值和首選值,然後讓佈局管理器完成其工作。您可以獲取paintComponent()中組件的寬度和高度,以根據其大小進行渲染。

+0

@Christian:在你關於這個主題的問題中有兩個相關的例子。 http://stackoverflow.com/questions/3646832 – trashgod 2010-09-06 01:25:47

相關問題