我想在一個非常簡單的環(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ā)生。
添加回答
舉報
0/150
提交
取消