How to set the previous jframe visible when curren

2019-09-03 06:25发布

I am making a Java gui project and it consists of two frames.

The problem is that when I call the secondframe from the firstframe, I have set it such that the firstframe visibility is set to false. The problem is how do I make the firstframe visible again by using a button from the second frame.

should i ditch this method and create a new jpanel instead??? Does jpanel have similar capabilities as jframe?

1条回答
欢心
2楼-- · 2019-09-03 06:53

Consider using CardLayout. This way you can switch via multiple UIs without needing another frame. Here's how to use it.

Edit: As Guillaume posted in his comment, this answer from Andrew also covers how to use the layout.

Edit2:
As you requested a little more information about my latest post, here's how such a class may look like:

import javax.swing.JFrame;


public abstract class MyFrameManager {
    static private JFrame   startFrame,
                        anotherFrame,
                        justAnotherFrame;

static public synchronized JFrame getStartFrame()
{
    if(startFrame == null)
    {
        //frame isnt initialized, lets do it
        startFrame = new JFrame();
        startFrame.setSize(42, 42);
        //...
    }

    return startFrame;
}

static public synchronized JFrame getAnotherFrame()
{
    if(anotherFrame == null)
    {
        //same as above, init it
    }

    return anotherFrame;
}

static public synchronized JFrame getJustAnotherFrame()
{
    //same again
    return justAnotherFrame;
}

public static void main(String[] args) {
    //let's test!

    JFrame start = MyFrameManager.getStartFrame();
        start.setVisible(true);

    //want another window
    JFrame another = MyFrameManager.getAnotherFrame();
        another.setVisible(true);

    //oh, doenst want start anymore
    start.setVisible(false);
}
}

This way you would only instantiate every JFrame once, but you could always access them via your manager class. What you do with them after that is your decision.
I also just made it thread-safe, which is crucial for singletons.

查看更多
登录 后发表回答