简体   繁体   中英

swing - how to switch JPanel using button

Hi guys I'm planning to create login panel. In that panel should be user JLabel, password JLabel, user JTextField, password JTextField, and JButon. I would like to use that button to switch to new JPanel. I've read the best way is CardLayout and I'm trying to modify that code:

//Where the GUI is assembled:
//Put the JComboBox in a JPanel to get a nicer look.
JPanel comboBoxPane = new JPanel(); //use FlowLayout
String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
...
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
...

//Method came from the ItemListener class implementation,
//contains functionality to process the combo box item selecting
public void itemStateChanged(ItemEvent evt) {
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
}

I'm trying to modify that part of code

JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);

and change it in to:

JButton loginButton = new JButton();
loginButton.addItemListener(this);
comboBoxPane.add(loginButton);
pane.add(loginButton, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);

I can't use:

JButton loginButton = new JButton(comboBoxItems);

because compiler return error: The constructor JButton(String[]) is undefined

is any one can help me with my problem. I'm newbie in Java programming

JButton does not have a constructor which takes a String array. It is sufficient to call:

JButton loginButton = new JButton("Login");

See: Creating a GUI With JFC/Swing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM