【发布时间】:2016-07-31 03:49:05
【问题描述】:
我遇到了一个问题,当我在我的代码中单击 JRadioButton 时,我的交互输出中出现了很多红线。该程序要求用户在“你最喜欢的水果是什么?”这个问题的四个答案中选择一个。这是代码的摘录:
//constructor
public Form(){
EventListener listener = new EventListener();
private class EventListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if ((JButton)e.getSource() == fruitButton) {
selectA = new JRadioButton("Apples");
selectA.addActionListener(listener);
selectB = new JRadioButton("Bananas");
selectB.addActionListener(listener);
selectC = new JRadioButton("Cherries");
selectC.addActionListener(listener);
selectD = new JRadioButton("Other");
selectD.addActionListener(listener);
if ((JButton)e.getSource() == quitButton) {
System.exit(1);
}
if (selectAButton.isSelected() || selectBButton.isSelected() || selectCButton.isSelected() || selectDButton.isSelected()) {
southPanel.add(submitButton);
}
}}
但是,当我在每次单击 JRadioButtons 选择之一时运行代码时,我会在交互输出中看到很多红线,开头是:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JRadioButton cannot be cast to javax.swing.JButton
我在同一个事件侦听器中有JButtons(例如,有一个退出按钮),但无论我做什么,一旦选择了单选按钮,我似乎都无法在底部添加提交按钮。请帮忙!
【问题讨论】:
-
通过
button声明提供完整代码 -
您正在无条件地将事件源转换为 JButton。当源是 JRadioButton 时,这会导致 ClassCastException。你必须先用 instanceof 检查你得到了什么,然后再进行转换。
标签: java jframe actionlistener event-listener jradiobutton