【问题标题】:Where is the place to setSize of subcomponents子组件的setSize的地方在哪里
【发布时间】: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


【解决方案1】:

组件的大小和位置由布局管理器设置,一帧初始化后调用pack()调整所有组件的大小。

您应该首先设置最小、最大和首选大小,然后让布局管理器完成其工作。您可以在 paintComponent() 中获取组件的宽度和高度,以根据其大小进行渲染。

【讨论】:

【解决方案2】:

如果您向我们展示一些代码并解释您正在尝试做什么,这将非常有帮助,但据我了解,您试图在一个 JPanel 中做太多事情。你应该有一个单独的面板来覆盖 paintComponent() 如果你打算在它上面绘图,等等,另一个(或更多)来保存你的其他组件。

实际上,调整单个组件的大小非常困难,因为它们必须遵守为其父组件(通常是 JPanel)选择的布局,因此您也必须牢记这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2013-10-28
    • 2011-05-14
    • 2019-09-04
    • 1970-01-01
    • 2022-10-18
    • 2011-03-12
    相关资源
    最近更新 更多