当前位置: 首页 > 面试题库 >

Java Swing GUI尝试/捕获块

黄沈浪
2023-03-14
问题内容

我只是在学习Java异常处理和Java。我制作了一个Swing
GUI,用户将在两个字段中输入整数,然后单击带有算术函数的单选按钮,答案将出现在第三个文本字段中。我想包含一个try /
catch块,以在用户将前两个字段之一留为空白或输入除整数以外的内容时捕获异常,以及如果用户尝试将其除以零则输入第二个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移至操作预先执行的方法,现在,仅当Java设置GUI时它们才在其中,当用户执行操作预先执行的操作(actionPreformed)时,这些方法将被调用,因此它们需要try-
捕获,而不是设置方法。

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块即可



 类似资料:
  • 我有一个存储过程似乎没有正确记录错误。 代码有错误,但 catch 块似乎未生效。 try块相当长,但错误部分很简单,并且在最后出现,所以我已经对此进行了预测。 proc失败的错误是我们的老朋友“列名或提供的值的数量与表定义不匹配”。我已经修复了这个错误 - 这是一个愚蠢的懒惰错误 - 但我感到困惑为什么我的错误日志记录过程似乎没有工作 - 没有行入到我的 ExtractsErrorLog 表中。

  • 问题内容: 我经常遇到如下情况: 仍然需要尝试-最终在内部捕获块。 克服此问题的最佳实践是什么? 问题答案: 写一个类,其中包含捕获和记录此类异常的方法,然后根据需要使用。 您最终会看到如下内容: 您的客户端代码将类似于: 更新: 自Java 7开始,各种JDBC接口都得到了扩展,而以上代码回答了原始问题,如果您直接针对JDBC API编写代码,则现在可以对其进行结构化:

  • 问题内容: 我一直在看代码,并且看到了尝试资源的机会。我以前使用过标准的try-catch语句,看起来它们在做同样的事情。所以我的问题是“ 尝试使用资源”与“尝试捕获 ”之间的区别是什么,哪个更好。 这是尝试使用资源: 问题答案: 尝试使用资源的重点是确保可靠地关闭资源。 当你不使用try-with-resources时,存在一个潜在的陷阱,称为异常屏蔽。当try块中的代码引发异常,而finall

  • 问题内容: 我有一个需要类似以下内容的场景 在我的尝试,我会,数据,将其与基于处理其他数据集。 在随后。有可能阻止吗?下面是伪代码: 问题答案: 无需创建表,您只需声明一个表变量(查询结束时该变量将自动消失)。

  • 我有一个返回< code>List的方法。现在我想知道如何正确放置< code>try/catch块。如果我将< code>return语句放在< code>try中,我会得到错误 并非所有代码路径都返回值 如果我放置在之后(就像我目前所做的那样),即使在之后,它也会返回。那么最好的方法应该是什么? 方法如下:

  • 问题内容: 下面的代码询问用户他/她想要多少个赛车手。 如果在代码中输入数字,则代码会跳出循环,并且程序的其余部分可以正常运行;但是,当我输入诸如“ awredsf”之类的内容时,它应该捕获该异常,并且确实如此。它没有连续提示用户,而是连续循环,这对我来说没有意义。 连续循环时,程序打印如下: 多少赛车手应该参加比赛?多少赛车手应该参加比赛?多少赛车手应该参加比赛?多少赛车手应该参加比赛?多少赛车