【发布时间】:2020-02-04 21:24:10
【问题描述】:
我想在一个非常简单的环境中使用 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上设置位置?
【问题讨论】:
-
在 while 循环中不断重绘是个坏主意。也许您可以改用
Timer。不太可能产生不必要的副作用。 -
JPanel的默认布局管理器可能会覆盖您对JLabel的显式定位。尝试在JPanel的构造函数中添加setLayout(nulll)。