2014-02-09 32 views
0

我只是在學習Java異常處理和Java。我製作了一個Swing GUI,用戶將整數輸入到兩個字段中,然後單擊帶算術功能的單選按鈕,答案將出現在第三個文本字段中。我想包含一個try/catch塊來捕獲異常,如果用戶將前兩個字段中的一個留空或者輸入除整數以外的內容,並且在用戶嘗試除以零時輸入其他內容。表單在功能上工作,但是錯誤不會被捕獲,只會返回堆棧跟蹤並導致程序崩潰。我有一種感覺,我只是把try/catch塊放在錯誤的地方,但我越是把它移到更糟糕的地方。有人能指出我出錯的地方嗎?Java Swing GUI Try/Catch Block

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.ButtonGroup; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JRadioButton; 
import javax.swing.JTextField; 

import javax.swing.WindowConstants; 
import javax.swing.SwingUtilities; 

public class Main extends javax.swing.JFrame { 
    private JTextField aTextField; 
    private JRadioButton dRadioButton; 
    private ButtonGroup buttonGroup; 
    private JLabel aLabel; 
    private JRadioButton cRadioButton; 
    private JRadioButton bRadioButton; 
    private JRadioButton aRadioButton; 
    private JTextField cTextField; 
    private JTextField bTextField; 

    /** 
    * Auto-generated main method to display this JFrame 
    */ 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       Main inst = new Main(); 
       inst.setLocationRelativeTo(null); 
       inst.setVisible(true); 
      } 
     }); 
    } 

    public Main() { 
     super(); 
     initGUI(); 
    } 

    private void initGUI() { 
     try { 
      setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 
      getContentPane().setLayout(null); 
      { 
       aTextField = new JTextField(); 
       getContentPane().add(aTextField); 
       aTextField.setBounds(12, 49, 62, 30); 
      } 
      { 
       bTextField = new JTextField(); 
       getContentPane().add(bTextField); 
       bTextField.setBounds(178, 49, 62, 31); 
      } 
      { 
       cTextField = new JTextField(); 
       getContentPane().add(cTextField); 
       cTextField.setBounds(297, 49, 62, 30); 
      } 
      { 
       aRadioButton = new JRadioButton(); 
       getContentPane().add(aRadioButton); 
       aRadioButton.setText("+"); 
       aRadioButton.setBounds(91, 18, 43, 20); 
       aRadioButton.setFont(new java.awt.Font("Segoe UI", 1, 16)); 
       aRadioButton.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent evt) { 
         aRadioButtonActionPerformed(evt); 
        } 
       }); 
       getButtonGroup().add(aRadioButton); 
      } 
      { 
       bRadioButton = new JRadioButton(); 
       getContentPane().add(bRadioButton); 
       bRadioButton.setText("-"); 
       bRadioButton.setBounds(91, 53, 43, 20); 
       bRadioButton.setFont(new java.awt.Font("Segoe UI", 1, 16)); 
       bRadioButton.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent evt) { 
         bRadioButtonActionPerformed(evt); 
        } 
       }); 
       getButtonGroup().add(bRadioButton); 
      } 
      { 
       cRadioButton = new JRadioButton(); 
       getContentPane().add(cRadioButton); 
       cRadioButton.setText("*"); 
       cRadioButton.setBounds(91, 99, 43, 20); 
       cRadioButton.setFont(new java.awt.Font("Segoe UI", 1, 16)); 
       cRadioButton.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent evt) { 
         cRadioButtonActionPerformed(evt); 
        } 
       }); 
       getButtonGroup().add(cRadioButton); 
      } 
      { 
       dRadioButton = new JRadioButton(); 
       getContentPane().add(dRadioButton); 
       getContentPane().add(getALabel()); 
       dRadioButton.setText("/"); 
       dRadioButton.setBounds(91, 140, 46, 20); 
       dRadioButton.setFont(new java.awt.Font("Segoe UI", 1, 16)); 
       dRadioButton.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent evt) { 
         dRadioButtonActionPerformed(evt); 
        } 
       }); 
       getButtonGroup().add(dRadioButton); 
      } 
      pack(); 
      setSize(400, 300); 
     } catch (NumberFormatException e) { 
      JOptionPane.showMessageDialog(null, 
        "Error: You must enter an integer"); 

     } catch (ArithmeticException e) { 
      JOptionPane.showMessageDialog(null, 
        "Error: You cannot divide by zero"); 
     } 
    } 

    private ButtonGroup getButtonGroup() { 
     if (buttonGroup == null) { 
      buttonGroup = new ButtonGroup(); 
     } 
     return buttonGroup; 
    } 

    private JLabel getALabel() { 
     if (aLabel == null) { 
      aLabel = new JLabel(); 
      aLabel.setText("="); 
      aLabel.setBounds(249, 56, 30, 16); 
      aLabel.setFont(new java.awt.Font("Segoe UI", 1, 16)); 
     } 
     return aLabel; 
    } 

    private void aRadioButtonActionPerformed(ActionEvent evt) { 
     String a = aTextField.getText(); 
     int i = Integer.parseInt(a); 
     String b = bTextField.getText(); 
     int j = Integer.parseInt(b); 
     int k = i + j; 
     cTextField.setText(Integer.toString(k)); 
    } 

    private void bRadioButtonActionPerformed(ActionEvent evt) { 
     String a = aTextField.getText(); 
     int i = Integer.parseInt(a); 
     String b = bTextField.getText(); 
     int j = Integer.parseInt(b); 
     int k = i - j; 
     cTextField.setText(Integer.toString(k)); 
    } 

    private void cRadioButtonActionPerformed(ActionEvent evt) { 
     String a = aTextField.getText(); 
     int i = Integer.parseInt(a); 
     String b = bTextField.getText(); 
     int j = Integer.parseInt(b); 
     int k = i * j; 
     cTextField.setText(Integer.toString(k)); 
    } 

    private void dRadioButtonActionPerformed(ActionEvent evt) { 
     String a = aTextField.getText(); 
     int i = Integer.parseInt(a); 
     String b = bTextField.getText(); 
     int j = Integer.parseInt(b); 
     int k = i/j; 
     cTextField.setText(Integer.toString(k)); 
    } 

    } 


Here is the stack trace I receive: 

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "vvvv" 
at java.lang.NumberFormatException.forInputString(Unknown Source) 
at java.lang.Integer.parseInt(Unknown Source) 
at java.lang.Integer.parseInt(Unknown Source) 
at Main.aRadioButtonActionPerformed(Main.java:154) 
at Main.access$0(Main.java:152) 
at Main$2.actionPerformed(Main.java:78) 
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) 
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) 
at javax.swing.JToggleButton$ToggleButtonModel.setPressed(Unknown Source) 
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) 
at java.awt.Component.processMouseEvent(Unknown Source) 
at javax.swing.JComponent.processMouseEvent(Unknown Source) 
at java.awt.Component.processEvent(Unknown Source) 
at java.awt.Container.processEvent(Unknown Source) 
at java.awt.Component.dispatchEventImpl(Unknown Source) 
at java.awt.Container.dispatchEventImpl(Unknown Source) 
at java.awt.Component.dispatchEvent(Unknown Source) 
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) 
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) 
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) 
at java.awt.Container.dispatchEventImpl(Unknown Source) 
at java.awt.Window.dispatchEventImpl(Unknown Source) 
at java.awt.Component.dispatchEvent(Unknown Source) 
at java.awt.EventQueue.dispatchEventImpl(Unknown Source) 
at java.awt.EventQueue.access$200(Unknown Source) 
at java.awt.EventQueue$3.run(Unknown Source) 
at java.awt.EventQueue$3.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) 
at java.awt.EventQueue$4.run(Unknown Source) 
at java.awt.EventQueue$4.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) 
at java.awt.EventQueue.dispatchEvent(Unknown Source) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) 
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) 
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
at java.awt.EventDispatchThread.run(Unknown Source) 
+1

該只會在單選按鈕動作偵聽器的上下文中引發異常,嘗試在try-catch語句中包裝這些方法的內容 – MadProgrammer

+0

Swing是一種事件驅動的環境,這意味着事情以非線性方式發生。當你的動作偵聽器被觸發時,initUI方法中的代碼已經執行,並且方法已經退出 – MadProgrammer

回答

2

您需要將您的try-catch移至動作預製的方法,現在,他們只是在Java正在建立GUI,當用戶瓶坯的動作(actionPreformed)這些方法會被調用,因此它們需要try-catch,而不是設置方法。

private void cRadioButtonActionPerformed(ActionEvent evt) { 
    try { 

      String a = aTextField.getText(); 
      int i = Integer.parseInt(a); 
      String b = bTextField.getText(); 
      int j = Integer.parseInt(b); 
      int k = i * j; 
      cTextField.setText(Integer.toString(k)); 

     } catch (NumberFormatException e) { 
      JOptionPane.showMessageDialog(null, 
       "Error: You must enter an integer"); 

     } catch (ArithmeticException e) { 
      JOptionPane.showMessageDialog(null, 
       "Error: You cannot divide by zero"); 
    } 
} 

在try-catch添加到所有使用這個類似的代碼,只是使ActionPreformed方法確保每個actionPreformed方法仍然有它自己的代碼,只需與周圍的try-catch塊

+1

非常好,這解決了我的問題,並幫助我理解爲什麼它以前不工作。我知道我把它放在了錯誤的地方,我無法弄清楚在哪裏放置它。謝謝!! – user2948381

+0

@ user2948381-但是如果用戶選擇單選按鈕,它會提示錯誤,無論用戶是否在任何字段中都沒有輸入。 看到我不同的答案 –

2

您應該將try catch塊放在Integer.parseInt()所調用的地方。

1

你」將獲得的例外,如果你不檢查你的每一個事件的方法,所以你可以做這樣的事情來解決這個問題,

private void aRadioButtonActionPerformed(ActionEvent evt) { 
    String a = aTextField.getText(); 
    String b = bTextField.getText(); 



    // you may get empty string here so check if the texbox is empty ? 
int i=0,j=0; 

     try{ 

    if(a.length()>0 || b.length()>0){ 
     i = Integer.parseInt(a); 
     j = Integer.parseInt(b); 
    }else{ 
     if(a.length()<1 && b.length()>0){ 

      i = Integer.parseInt(a); 
     }else{ 
      if(b.length()<1 && a.length()>0) 
      j = Integer.parseInt(b); 
     } 
    } 


    int k = i + j; 
     }catch(Exception e){ 
      System.out.println("Exception:"+e); 
      } 
    cTextField.setText(Integer.toString(k)); 
} 

做同樣的事情爲你 - ,*,/單選按鈕聽衆太