user3418987
user3418987

Reputation: 137

How do you open a new JPanel window on a click of a button?

I am new to JSwing and I would like to ask a question regarding opening new JPanels on a click of a button.

public class GUIDriver extends JFrame implements ActionListener {

private JPanel mainPanel;
private JButton regButton;
private JButton loginButton;
private JButton acctButton;

public GUIDriver(){

    super("FriendBook");
    mainPanel = new JPanel();
    regButton = new JButton("Register Account");
    loginButton = new JButton("Login");
    acctButton = new JButton("View Accounts");

    mainPanel.add(regButton);
    mainPanel.add(loginButton);
    mainPanel.add(acctButton);

    regButton.addActionListener(this);
    loginButton.addActionListener(this);
    acctButton.addActionListener(this);
    getContentPane().add(mainPanel);
    setSize(300,300);
}

public static void main(String[] args){

    GUIDriver myDriver = new GUIDriver();

    myDriver.setVisible(true);
    myDriver.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}


@Override
public void actionPerformed(ActionEvent e){

    if(e.getSource() == regButton){

        JPanel register = new JPanel();
        register.setSize(new Dimension(400,100));
        JLabel username = new JLabel("Username");
        JLabel password = new JLabel("Password");
        JButton registerBT = new JButton("Register Account");
        JTextField uname = new JTextField(20);
        JTextField pass = new JTextField(20);
        register.add(username);
        register.add(uname);
        register.add(password);
        register.add(pass);
        register.add(registerBT);

        register.setVisible(true);



}
    else if(e.getSource() == loginButton){

        System.out.print("LOGIN");
    }

    else if (e.getSource() == acctButton){

        System.out.print("VIEW ACCOUNTS");
    }
}

}

The programs shows three buttons (Register, Login and View). I would like to open a new JPanel window when I click on the Register button but it does not show. Please help me, I am new to JSwing/Java GUI. Thank you!

Upvotes: 2

Views: 5699

Answers (1)

GhostCat
GhostCat

Reputation: 140427

A JPanel needs something that wraps around in order to be displayed; you have to create another "windows"; for example a JDialog. Then you add the created panel to that "window".

In other words: just creating a JPanel is not sufficient to make it visible.

Upvotes: 1

Related Questions