而无需调整其大小

而无需调整其大小

本文介绍了如何在JFrame可见时将组件添加到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时,除非调整JFrame的大小(我使用的是Windows 7),否则该红色JPanel不会变为可见.有没有一种方法可以实现我想要的而无需手动调整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. */
    }
}

推荐答案

用于删除(然后添加新的JComponent),例如 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();

如果仅调整JComponent的大小或更改它,则:

And if you only resize or change JComponents:

validate();
repaint();

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

08-04 07:36