为什么我必须在每个 paintComponent 上设置我的 JLabel 的位置?

Why do I have to set the position of my JLabel on every paintComponent?

我想在一个非常简单的环境中使用 JLabel,但我想知道为什么我必须在每次重绘时设置位置。

代码:

public class Example {
    public static void main(String[] args) {
        JFrame frame = buildFrame();
        TestPane pane = new TestPane();

        frame.add(pane);

        while (true) {
            pane.repaint();
            frame.setVisible(true);
        }
    }

    private static JFrame buildFrame() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(480, 272);
        frame.setVisible(true);
        return frame;
    }
}

public class TestPane extends JPanel {
    JLabel testLabel = new JLabel("TEST");

    TestPane() {
        super();
        add(testLabel);
        testLabel.setLocation(200, 200);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        testLabel.setLocation(200, 200); // without this line, the label will always be at the top center
    }
}

基于循环的布局来自我正在制作的各种带有图像的动画。为什么重绘总是重置所有标签的位置,所以我必须在每个 paintComponent 上设置位置?

why I have to set the location on every repaint.

你不知道。实际上,你永远不应该在 paintComponent 方法中设置组件的位置或任何类型的约束。 paintComponent方法只用于绘画,不用于定位或其他任何东西。

当你jpanel.add(myComponent, constraints)组件的位置将由容器的当前LayoutManager决定。 (当你 jpanel.add(myComponent); 没有任何约束时,默认约束将会发生,每个布局管理器都有自己的默认值)。

标签位于面板的顶部,因为您没有设置面板的布局,所以它有默认值,即 FlowLayout. 要更改它,您将不得不使用另一个具有适当约束的布局管理器。

例如,为了将它放在面板的中央,您必须这样做:

jpanel.setLayout(new BorderLayout());
jpanel.add(myLabel,BorderLayout.CENTER);

最后在 GUI 所在的线程中执行 while(true) 运行,它会挂起线程,这意味着 GUI 将 "frozen" 因为事件无法发生。