为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

MMMHUHU 2023-09-27 21:28:04
我想在一个非常简单的环境中使用 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 上设置位置?
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

为什么我必须在每次重画时设置位置。

你不知道。实际上,您永远不应该在方法内设置组件的位置或任何类型的约束paintComponentpaintComponent方法仅用于绘画,不用于定向或其他任何用途。

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

标签放置在面板的顶部,因为你没有设置面板的布局,所以它有它的默认值,即FlowLayout。为了更改它,您必须使用另一个具有适当约束的布局管理器。

例如,为了将其放置在面板的中心,您必须执行以下操作:

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

最后while(true)在 GUI 运行的线程中执行,它将挂起线程,意味着 GUI 将被“冻结”,因为事件无法发生。


查看完整回答
反对 回复 2023-09-27
  • 1 回答
  • 0 关注
  • 57 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信