【问题标题】:JRadioButton cannot be cast to JButtonJRadioButton 不能转换为 JButton
【发布时间】:2011-12-14 21:41:32
【问题描述】:

我有actionPerformed() 方法,它做了两件事:打印出选中的单选按钮并设置另一个类中标签的可见性。单击单选按钮时,我得到 cannot be cast to 错误。

public void actionPerformed(ActionEvent e)
{
    System.out.println("Selected: " + e.getActionCommand());
    JButton hiddenBtn = (JButton) e.getSource();
    if (hiddenBtn == submit)
    {
        Class o = new Class();
        o.foo();
    }
    JButton close = (JButton) e.getSource();
    if (close == purchase)
    {
        System.exit(0);
    }
}

我在(JButton) e.getSource() 收到错误消息。

【问题讨论】:

    标签: java swing jbutton jradiobutton


    【解决方案1】:

    JRadioButton 不扩展 JButton。因此,您不能将其转换为 JButton。但是,您可以转换为 AbstractButton。

    java.lang.Object java.awt.组件 java.awt.Container javax.swing.JComponent javax.swing.AbstractButton javax.swing.JToggleButton javax.swing.JRadioButton

    【讨论】:

      【解决方案2】:

      JButton 和 JRadioButton 的最小上限是AbstractButton。我认为,你可以投射到那个地方,做你想做的事。

      【讨论】:

        【解决方案3】:

        除了转换是否有效的技术方面,逻辑上思考用 JButton 转换 JRadioButton 背后的原因。两者的用法不同。

        【讨论】:

          【解决方案4】:

          与AbstractButton 或JButton 连接使用ButtonGroup,因为如果将JRadioButton(s) 添加到ButtonGroup,则只能选择一个JRadioButton,

          我可以模拟这个错误,关于 cannot be cast to javax.swing.AbstractButton or cannot be cast to javax.swing.JButton from the uncorrect usage renderer in the JTable

          【讨论】:

          • > 95 % 与问题无关
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-10-09
          • 2015-02-20
          • 1970-01-01
          • 1970-01-01
          • 2015-05-21
          • 2016-05-14
          • 2016-07-20
          相关资源
          最近更新 更多