【问题标题】:Java Swing GUI Try/Catch BlockJava Swing GUI Try/Catch 块
【发布时间】:2014-02-09 19:59:29
【问题描述】:

我只是在学习 Java 异常处理和一般的 Java。我制作了一个 Swing GUI,用户将在两个字段中输入整数,然后单击带有算术函数的单选按钮,答案将出现在第三个文本字段中。如果用户将前两个字段之一留空或输入整数以外的其他内容,我想包含一个 try/catch 块来捕获异常,如果用户尝试除以零,我想包含第二个捕获。该表单在功能上工作,但是错误没有被捕获,只返回堆栈跟踪并使程序崩溃。我有一种感觉,我只是将 try/catch 块放在了错误的位置,但我移动它的次数越多,情况就越糟糕。有人能指出我哪里出错了吗?

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)

【问题讨论】:

  • 只有在单选按钮动作监听器的上下文中才会引发异常,尝试将这些方法的内容包装在 try-catch 语句中
  • Swing 是一个事件驱动的环境,这意味着事情以非线性方式发生。当你的动作监听器被触发时,你的 initUI 方法中的代码已经执行并且该方法已经退出

标签: java swing try-catch


【解决方案1】:

您需要将您的 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 块

【讨论】:

  • 非常好,它解决了我的问题并帮助我理解了为什么它以前不起作用。我知道我把它放错了地方,我只是不知道该放在哪里。谢谢!!
  • @user2948381- 但是如果用户选择单选按钮,它会提示错误,无论用户没有在任何字段中输入。查看我的不同答案
【解决方案2】:

你应该把 try catch 块放在你的Integer.parseInt() 调用的地方。

【讨论】:

    【解决方案3】:

    如果你不检查你的每一个事件方法,你会得到异常,所以你可以做类似的事情来解决它,

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

    也为你做同样的事情 -,*,/ 单选按钮听众

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-01
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多