简体   繁体   English

JRadioButton无法转换为JButton

[英]JRadioButton cannot be cast to JButton

I have actionPerformed() method which does two things: print out the radio buttons selected and set visibility of labels in another class. 我有actionPerformed()方法,该方法执行两件事:打印出选中的单选按钮,并设置另一个类中标签的可见性。 I get cannot be cast to error when the radio button is clicked. 单击单选按钮时,我无法转换为错误。

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);
    }
}

I get the error at (JButton) e.getSource() . 我在(JButton) e.getSource()处收到错误。

JRadioButton does not extend JButton . JRadioButton不扩展JButton Therefore, you cannot cast it to a JButton . 因此,您不能将其JButton转换为JButton You can, however, cast to an AbstractButton . 但是,您可以强制转换为AbstractButton

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

Their least upper bound of JButton and JRadioButton is AbstractButton . 它们的JButton和JRadioButton的最小上限是AbstractButton You can cast to that, i think, to do what you want. 我认为,您可以按照自己的意愿去做。

Besides the technical aspect of whether or not casting works, think logically on the reason behind casting a JRadioButton with a JButton. 除了强制转换是否起作用的技术方面,还要逻辑地考虑使用JButton强制转换JRadioButton的原因。 The usage of both are different. 两者的用法不同。

In connection with AbstractButton or JButton use ButtonGroup , because if you add JRadioButton(s) to the ButtonGroup , then only one JRadioButton could be selected, AbstractButtonJButton使用ButtonGroup ,因为如果将JRadioButton(s)添加到ButtonGroup ,则只能选择一个JRadioButton

I can simulating this error about cannot be cast to javax.swing.AbstractButton or cannot be cast to javax.swing.JButton from un-correct usage renderer in the JTable 我可以模拟此错误,因为它无法从JTable不正确用法渲染器转换为javax.swing.AbstractButton或无法转换为javax.swing.JButton

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM