[英]JPanel drawing - why do I have to override paintComponent method?
[英]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上設置位置?
為什么我必須在每次重繪時設置位置。
你沒有。 實際上,您永遠不應該在paintComponent
方法中設置 position 或任何類型的組件約束。 paintComponent
方法僅用於繪畫,而不用於方向或其他任何事情。
當您jpanel.add(myComponent, constraints)
組件的 position 將由容器的當前LayoutManager決定。 (當您jpanel.add(myComponent);
沒有任何約束時,將發生默認約束,每個布局管理器都有自己的默認值)。
label因為沒有設置面板的布局,所以放在面板的最上方,所以有它的默認,就是FlowLayout。 為了改變它,你將不得不使用另一個具有適當約束的布局管理器。
例如,要將其放置在面板的中心,您必須執行以下操作:
jpanel.setLayout(new BorderLayout());
jpanel.add(myLabel,BorderLayout.CENTER);
最后在運行 GUI 的線程內執行while(true)
,它將掛起線程,這意味着 GUI 將被“凍結”,因為事件無法發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.