【发布时间】:2011-04-08 12:45:55
【问题描述】:
我从 JPanel 扩展了课程。这个类包含几个其他的 JComponents 和大量的绘画。我所做的但我知道这是不正确的,我覆盖了绘画的paintComponent,到目前为止一切都很好。
但是我还在这个方法中设置了所有子组件的位置和大小,因为它们依赖于 JPanel 中的 getWidth 和 getHeight。我知道这不是组件的地方,但我在哪里做这种事情。在构造函数时,未设置大小。那么如何纠正呢?因为只要我在paintComponent方法中有location和size方法,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());
}
}
一切正常,除了我的 CPU 使用率总是在 10% 左右。如果将两条线都去掉,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 */ }
}
【问题讨论】:
-
重新格式化的代码;如果不正确,请恢复。
标签: java swing layout components jpanel