我有從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 */ }
}
重新格式化的代碼;如果不正確請回復。 – trashgod 2010-09-06 17:16:39