Java Swing GUI Try / Catch Block [英] Java Swing GUI Try/Catch Block

查看:142
本文介绍了Java Swing GUI Try / Catch Block的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习Java异常处理和Java。我做了一个Swing GUI,用户将整数输入两个字段,然后单击带有算术功能的单选按钮,答案将出现在第三个文本字段中。我希望包含一个try / catch块来捕获异常,如果用户将前两个字段中的一个留空或者输入除整数之外的其他字段,如果用户试图除以零则返回第二个字段。该表单在功能上有效,但不会捕获错误,只返回堆栈跟踪并使程序崩溃。我有一种感觉,我只是在错误的地方有try / catch块,但是我越是将它移动到更糟糕的地方。有人可以指出我哪里出错吗?

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 arithmetic function and the answer will appear in a third text field. I want to include a try/catch block to catch exceptions if the user leaves one of the first two fields blank or enters something other than integers and a second catch if the user tries to divide by zero. The form works functionally, however the errors aren't caught and only return the stack trace and crash the program. I have a feeling I just have the try/catch block in the wrong place but the more I move it around the worse things get. Could somebody point to where I went wrong?

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)


推荐答案

你需要移动你的尝试抓住行动预先形成的方法,现在,他们只有当Java正在设置GUI时,当用户预先形成动作(actionPreformed)时才会调用这些方法,因此它们需要try-catch,而不是setup方法。

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

将try-catch添加到所有ActionPreformed方法中使用这个类似的代码,只需确保每个actionPreformed方法仍然拥有它自己的代码,只需使用它周围的try-catch块

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

这篇关于Java Swing GUI Try / Catch Block的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆