如何在JFrame可见的情况下将组件添加到JFrame而无需调整大小?

时间:2011-07-01 11:28:38

标签: java swing jframe jpanel resize

我有一个程序,其中JFrame包含JButton。当用户点击JButton时,Components的所有JFrame都会被删除,并且会向其添加带有红色背景的JPanel

当我点击JButton时,除非我调整JPanel(我使用的是Windows 7),否则红色JFrame不会显示。有没有办法实现我想要的,而无需手动调整JFrame

以下是我正在使用的代码的一部分:

public class Demo implements ActionListener{
    public static void main(String args[]){
           ...............
        button.addActionListener(this); //'button' is an object of Jbutton class.
        frame.setVisible(true); //'frame' is an object of JFrame class.
        ............
    }

    public void actionPerformed(ActionEvent ae){
        frame.removeAllComponents();
        frame.add(panel1); //panel1 is an object of Jpanel class with red  background.

        /* Here is where my problem lies.
           panel1 is not visible to me unless I manually resize the JFrame. */
    }
}

3 个答案:

答案 0 :(得分:5)

要从JComponentsJPanel移除(然后,例如,添加新的JComponents)top-level containers,只需执行一次,并且在操作结束时:< / p>

revalidate();
repaint();

如果您只调整大小或更改JComponents:

validate();
repaint();

答案 1 :(得分:4)

对我来说,这有点奇怪。事实证明,调用remove(Component comp),添加新的JPanel,然后调用pack()为我工作。

public class Demo{

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel();
        final JButton button = new JButton("Press Me");
        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                frame.remove(panel);

                final JPanel redPanel = new JPanel(){

                    @Override
                    public Dimension getPreferredSize(){
                        return new Dimension(200, 200);
                    }

                    @Override
                    protected void paintComponent(Graphics g){
                        Graphics g2 = g.create();

                        g2.setColor(Color.RED);
                        g2.fillRect(0, 0, getWidth(), getHeight());

                        g2.dispose();
                    }
                };

                frame.add(redPanel);
                frame.pack();
            }
        });

        panel.add(button);
        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

在按下按钮之前

enter image description here

按下按钮后

enter image description here

<强>古怪

  1. 调用removeAll()实际上导致GUI冻结。似乎此事件已发生before。即使在我删除所有组件之前尝试删除动作侦听器之后,也会发生这种情况。
  2. 我不需要调用任何验证方法,甚至不需要重新绘制GUI。

答案 2 :(得分:-1)

你必须在框架中强制重绘(),这样框架必须自己重绘。