Question

i have a JPanel like:

public class CardLayoutPanel extends JPanel {
String[] option = {"login", "register"}    
public CardLayoutPanel() {
    super();
    combo_box = new JComboBox(option);
    login_panel = new LoginForm();
    register_panel = new RegisterForm();

    layout = new CardLayout();
    this.setLayout(new BorderLayout());
    panel = new JPanel();
    panel.setLayout(layout);

    this.add(combo_box, BorderLayout.NORTH);
    this.add(panel, BorderLayout.SOUTH);

    panel.add(login_panel, "login");
    panel.add(register_panel, "register");

    layout.show(panel, "login");
    combo_box.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JComboBox source = (JComboBox) e.getSource();

            if(source.getSelectedItem().equals("login")) {
                layout.show(panel, "login");
            }else if(source.getSelectedItem().equals("register")) {
                layout.show(panel, "register");
            }
        }
    });
}

}

and i call from my main calss inside a JOptionPane

CardLayoutPanel card_panel = new CardLayoutPanel();

    int res = JOptionPane.showConfirmDialog(null, card_panel, "Login/Registrati",JOptionPane.OK_CANCEL_OPTION);

Now, if i try to obtain the current visible card like

if(res == JOptionPane.OK_OPTION) {
        for(Component comp : card_panel.getComponents()) {
            if(comp.isVisible() == true) {
                JPanel current_panel = (JPanel) comp;

                System.out.println(current_panel.getName());
            }
        }
    }else if(res == JOptionPane.CANCEL_OPTION) {
        System.exit(-1);
    }

i obtain the sequent error:

Exception in thread "main" java.lang.ClassCastException: javax.swing.JComboBox cannot be cast to javax.swing.JPanel

on this row inside for each statement:

JPanel current_panel = (JPanel) comp;

how can i fix it?

Was it helpful?

Solution

I would simply get the JComboBox and query its selected item. Assuming that the class that holds the JComboBox has a method say called, getComboBox():

JComboBox combo = getComboBox();
String selectedItem = combo.getSelectedItem().toString();
System.out.println(selectedItem);

Alternatively and probably better for the class that holds the combo box to have a method that doesn't expose the combo box itself but allows other classes to query the combobox for the selected item.

public Object getComboBoxSelection() {
  combo_box.getSelectedItem();
}

And then outside classes can call this method on a valid reference.

OTHER TIPS

Not sure you are using the CardLayout correctly. I don't know why you would add a CardLayout to a JOptionPane. I would just add the panel you want to display.

But if you really want to know the currently display card in a CardLayout then check out Card Layout Focus which has a method to do this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top