从 BoxLayout 中移除时组件不会移动
我正在使用 BoxLayout 并动态地从中删除组件,如下所示:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
final JLabel l = new JLabel("remove");
frame.add(l);
frame.add(new JLabel("Hello2"));
frame.add(new JLabel("Hello3"));
frame.pack();
frame.setVisible(true);
new Thread() {
public void run() {
Utils.sleep(1000);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.remove(l);
frame.repaint();
}
});
}
}.start();
}
});
}
但是,在这样做时,即使有问题的标签已从布局中删除,其他组件也不会向上移动以覆盖其空间,直到我调整大小框架。我尝试在移除组件后重新绘制框架,但没有运气 - 标签不再显示,但仍然存在原来的间隙。
除了每次删除组件时自动调整窗口大小的明显可怕的困境之外,我如何获得所需的行为?
I'm using a BoxLayout and removing components from it dynamically, something like this:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
final JLabel l = new JLabel("remove");
frame.add(l);
frame.add(new JLabel("Hello2"));
frame.add(new JLabel("Hello3"));
frame.pack();
frame.setVisible(true);
new Thread() {
public void run() {
Utils.sleep(1000);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.remove(l);
frame.repaint();
}
});
}
}.start();
}
});
}
However, when doing so, even though the label in question is removed from the layout, the other components don't shift up to cover its space until I resize the frame. I tried repainting the frame after removing the component, but no luck - the label no longer displays but there's still the gap where it used to be.
Apart from the obviously horrible bodge of resizing the window automatically every time the component is removed, how do I get the desired behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要调用
validate()
也在frame
上。You need to invoke
validate()
onframe
as well.1/放置
revalidate()
;在repaint()
之前;2/ 更好的是从
Runnable
调用Thread
,而不是从invokeLater()
1/ put
revalidate()
; beforerepaint()
;2/ better would be invoke
Thread
fromRunnable
not frominvokeLater()