![](/img/trans.png)
[英]JRadioButton cannot be cast to JButton in EventListener
[英]JRadioButton cannot be cast to JButton
我有actionPerformed()
方法,該方法執行兩件事:打印出選中的單選按鈕,並設置另一個類中標簽的可見性。 單擊單選按鈕時,我無法轉換為錯誤。
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()
處收到錯誤。
JRadioButton
不擴展JButton
。 因此,您不能將其JButton
轉換為JButton
。 但是,您可以強制轉換為AbstractButton
。
java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.AbstractButton javax.swing.JToggleButton javax.swing.JRadioButton
它們的JButton和JRadioButton的最小上限是AbstractButton 。 我認為,您可以按照自己的意願去做。
除了強制轉換是否起作用的技術方面,還要邏輯地考慮使用JButton強制轉換JRadioButton的原因。 兩者的用法不同。
與AbstractButton
或JButton
使用ButtonGroup ,因為如果將JRadioButton(s)
添加到ButtonGroup
,則只能選擇一個JRadioButton
,
我可以模擬此錯誤,因為它無法從JTable
不正確用法渲染器轉換為javax.swing.AbstractButton
或無法轉換為javax.swing.JButton
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.