簡體   English   中英

無法將JRadioButton強制轉換為EventListener中的JButton

[英]JRadioButton cannot be cast to JButton in EventListener

我遇到一個問題,當我在代碼中單擊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 (例如,有一個退出按鈕),但是無論我做什么,一旦選擇了單選按鈕,我似乎都無法使Submit按鈕添加到底部。 請幫忙!

在強制轉換之前檢查事件源是否確實是JButton:

    if(e.getSource() instanceof JButton  && (JButton)e.getSource() == quitButton) {

            System.exit(1);
    }  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM