Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

java - How to add components to JFrame once it's visible without having to resize it?

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.

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. */
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

And if you only resize or change JComponents:

validate();
repaint();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...