第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

為什么我必須在每個 PaintComponent 上設(shè)置 JLabel 的位置?

為什么我必須在每個 PaintComponent 上設(shè)置 JLabel 的位置?

MMMHUHU 2023-09-27 21:28:04
我想在一個非常簡單的環(huán)境中使用 JLabel,但我想知道為什么我必須在每次重繪時設(shè)置位置。代碼: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    }}基于循環(huán)的布局來自我正在制作的帶有圖像的各種動畫。為什么重繪總是重置所有標簽的位置,所以我必須在每個 PaintComponent 上設(shè)置位置?
查看完整描述

1 回答

?
臨摹微笑

TA貢獻1982條經(jīng)驗 獲得超2個贊

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

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

當您組件的位置將由容器當前的LayoutManagerjpanel.add(myComponent, constraints)決定。(當您沒有任何約束時,將發(fā)生默認約束,每個布局管理器都有自己的默認約束)。jpanel.add(myComponent);

標簽放置在面板的頂部,因為你沒有設(shè)置面板的布局,所以它有它的默認值,即FlowLayout。為了更改它,您必須使用另一個具有適當約束的布局管理器。

例如,為了將其放置在面板的中心,您必須執(zhí)行以下操作:

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

最后while(true)在 GUI 運行的線程中執(zhí)行,它將掛起線程,意味著 GUI 將被“凍結(jié)”,因為事件無法發(fā)生。


查看完整回答
反對 回復 2023-09-27
  • 1 回答
  • 0 關(guān)注
  • 95 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號