亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我必須在每個 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個贊

為什么我必須在每次重畫時設置位置。

你不知道。實際上,您永遠不應該在方法內設置組件的位置或任何類型的約束paintComponent。paintComponent方法僅用于繪畫,不用于定向或其他任何用途。

當您組件的位置將由容器當前的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 關注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號