Java Swing GUI Try/Catch Block

后端 未结 3 1075
刺人心
刺人心 2021-01-29 05:04

I\'m just learning Java exception handling and Java in general. I\'ve made a Swing GUI where the user will enter integers into two fields and then click a radio button with an

相关标签:
3条回答
  • 2021-01-29 05:34

    You should put the try catch block where your Integer.parseInt() calls.

    0 讨论(0)
  • 2021-01-29 05:50

    You'll get exception if you won't check your every event method, so you can do something like that to solve it,

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

    do the same thing for you -,*,/ radio button listeners too

    0 讨论(0)
  • 2021-01-29 05:51

    You need to move your try-catch to the action preformed methods, right now, they are only in when Java is setting up the GUI, when the user preforms the action (actionPreformed) those methods will be called, therefore they need the try-catch, not the setup method.

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

    Add the try-catch to all the ActionPreformed methods that use this similar code, just make sure each actionPreformed method still has it's own code, just with the try-catch block around it

    0 讨论(0)
提交回复
热议问题