开发者

Components not shifting when removing from BoxLayout

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开发者_JS百科 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?


You need to invoke validate() on frame as well.


SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        frame.remove(l);
        frame.validate();
        frame.repaint();
    }
});


1/ put revalidate(); before repaint();

2/ better would be invoke Thread from Runnable not from invokeLater()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜