我有一个JPanel,例如:
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");
}
}
});
}
}
我从 JOptionPane 中的主类调用
CardLayoutPanel card_panel = new CardLayoutPanel();
int res = JOptionPane.showConfirmDialog(null, card_panel, "Login/Registrati",JOptionPane.OK_CANCEL_OPTION);
现在,如果我尝试获取当前可见的卡片,例如
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);
}
我得到后续错误:
线程“主”java.lang.ClassCastException 中的异常:javax.swing.JComboBox 无法转换为 javax.swing.JPanel
在每个语句里面的这一行:
JPanel current_panel = (JPanel) comp;
我该如何解决?