BorderLayout-添加另一个组件后,子组件仍然可见 [英] BorderLayout - child component remains visible after adding another component
问题描述
我尝试执行以下操作:
- 使用
BorderLayout
将组件添加到 - 将另一个组件添加到
JFrame
JFrame
由于我使用的是BorderLayout
,因此我希望新组件覆盖"旧组件.如果在调用pack()
之前覆盖了旧组件,则可以使用此功能.现在,如果我在之后添加第二个组件,则调用pack()
,这两个组件都保持可见.示例:
I would expect the new component to 'overwrite' the old component, since I'm using a BorderLayout
. This works if I overwrite the old component before I call pack()
. Now if I add the 2nd component after I call pack()
, both components remain visible. Example:
public class Test extends JFrame{
public Test(){
setLayout(new BorderLayout());
add(new JLabel("Quite a long text"));
setVisible(true);
pack();
add(new JLabel("Another text"));
}
}
结果:
public class Test extends JFrame{
public Test(){
setLayout(new BorderLayout());
add(new JLabel("Quite a long text"));
setVisible(true);
add(new JLabel("Another text"));
pack();
}
}
结果:
我尝试添加validate();
和repaint();
,但这无济于事.这是怎么了
I tried adding validate();
and repaint();
, but that wouldn't help. What's going wrong here?
推荐答案
在调用setViisble()之后,您正在调用会影响UI的事物-Swing不行.将影响用户界面的内容放入invokeLater调用中;查找它.
You are calling things that affect the UI after setViisble() is called -- a Swing no-no. Put things that affect the UI into an invokeLater call; look it up.
在使用它时,我认为您仍然应该从框架中获取内容窗格以添加组件...而且我认为在构造函数中创建东西不是一个好主意.
While you're at it, I think you're still supposed to get the content pane from the frame for adding components... And I don't think creating things in the constructor is a good idea.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class SwingTest extends JFrame
{
public void createUI()
{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
getContentPane().setLayout(new BorderLayout());
getContentPane().add(new JLabel("Quite a long text"), BorderLayout.CENTER);
getContentPane().add(new JLabel("Another text"), BorderLayout.CENTER);
pack();
setVisible(true);
}
}
);
}
public static void main(String ... args)
{
SwingTest st = new SwingTest();
st.createUI();
}
}
这篇关于BorderLayout-添加另一个组件后,子组件仍然可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!