一旦可见,如何将组件添加到 JFrame 而无需调整它的大小? [英] How to add components to JFrame once it's visible without having to resize it?

查看:43
本文介绍了一旦可见,如何将组件添加到 JFrame 而无需调整它的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,其中有一个 JFrame 和一个 JButton.当用户点击JButton时,JFrame的所有Components都被移除,红色背景的JPanel添加到它.

I have a program where I have a JFrame with a JButton in it. When the user clicks the JButton, all Components of the JFrame are removed, and a JPanel with red background is added to it.

当我单击 JButton 时,红色的 JPanel 不会变得可见,除非我调整 JFrame 的大小(我使用的是 Windows 7).有没有办法实现我想要的,而无需手动调整 JFrame 的大小?

When I click the JButton, that red JPanel does not become visible unless I resize the JFrame (I am using Windows 7). Is there a way to achieve what I want without having to manually resize the JFrame?

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

Here is a part of the code I am using:

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. */
    }
}

推荐答案

用于删除(然后,例如,添加新的 JComponents)JComponents 来自 JPanel 或来自 顶级容器您只需调用一次,并且在操作结束时调用:

For removing (and then, for example, add new JComponents) JComponents from JPanel or from top-level containers you have to call, only once and on the end of the action:

revalidate();
repaint();

如果您只调整或更改 JComponents:

And if you only resize or change JComponents:

validate();
repaint();

这篇关于一旦可见,如何将组件添加到 JFrame 而无需调整它的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆