Java - 开始按钮和新的 JFrame

Java - Start Button and new JFrame

我必须确保在按下开始游戏按钮时打开游戏框。

这是菜单:

这是控制器class:

@Override
public void actionPerformed(ActionEvent e) {
    JRadioButton source = (JRadioButton)e.getSource();
    JButton sourceButton = (JButton)e.getSource();

    if(source.isSelected() && source.getText().equals("Custom")){
        MenuView.heightLabel.setEnabled(true);
        MenuView.height.setEnabled(true);

        MenuView.widthLabel.setEnabled(true);
        MenuView.width.setEnabled(true);

        MenuView.minesLabel.setEnabled(true);
        MenuView.mines.setEnabled(true);
    }
    else{
        MenuView.heightLabel.setEnabled(false);
        MenuView.height.setEnabled(false);

        MenuView.widthLabel.setEnabled(false);
        MenuView.width.setEnabled(false);

        MenuView.minesLabel.setEnabled(false);
        MenuView.mines.setEnabled(false);
    }

    if(source.getText().equals("Beginner")){
        if(sourceButton.getText().equals("Start Game")){
            MenuView.fullRandom = new FullRandomGrid(ROW_BEGINNER, COLUMN_BEGINNER, MINE_BEGINNER);
            Frame frame = new Frame(MenuView.fullRandom);
            frame.setSize(270, 380);
            frame.setResizable(false);
            frame.setVisible(true);

        }
    }   
}

问题是当我按下 Start Game 时出现异常:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JRadioButton

问题在行 JRadioButton source = (JRadioButton)e.getSource(); - 您按下 JButton 对象,这会导致事件,然后您将错误的 JButton 类型转换为 JRadioButton。

问题出在这一行:

JRadioButton source = (JRadioButton)e.getSource();

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

JRadioButton 不是 e.getSource() 的子类,因此会抛出 ClassCastException。


JRadioButton source = (JRadioButton)e.getSource();
JButton sourceButton = (JButton)e.getSource();

如何在没有子父关系的情况下在两者中都使用 e.getSource()