整数不会出现在 TextField 中

Integer won't appear in a TextField

我的程序有问题。我试图在文本字段中输入一个整数。这是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.MouseEvent.*;

public class GradingSystem extends JFrame{

    public GradingSystem(){
        super("Grading System");
        JLabel pre = new JLabel ("PRELIM GRADE: ");
        final JTextField pre1 = new JTextField(10);
        JLabel mid = new JLabel("MIDTERM GRADE: ");
        final JTextField mid1 = new JTextField(10);
        JLabel fin = new JLabel ("FINAL GRADE: ");
        final JTextField fin1 = new JTextField(10);
        JLabel ave = new JLabel("AVERAGE: ");
        final JTextField  ave1 = new JTextField(10);
        JButton calculate = new JButton("CALCULATE");
        FlowLayout flo = new FlowLayout();
        setLayout(flo);
        add(pre);
        add(pre1);
        add(mid);
        add(mid1);
        add(fin);
        add(fin1);
        add(ave);
        add(ave1);
        add(calculate);
        setSize(315,150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

        calculate.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){
                try{
                    int i1 = Integer.parseInt(pre1.getText());
                    int i2 = Integer.parseInt(mid1.getText());
                    int i3 = Integer.parseInt(fin1.getText());
                    int i4 = Integer.parseInt(ave1.getText());

                    i4 = (i1 + i2 + i3) / 3;


                    ave1.setText(String.valueOf(i4));
                }catch(Exception ex){

                }
            }

        });



    }

    public static void main(String[] a){
        GradingSystem gs = new GradingSystem();
    }

}

我正在尝试让 ave1.setText(String.valueOf(i4)); 出现在文本字段中,但它不会。
我究竟做错了什么?

只有当您单击“计算”按钮时,您才会在文本字段中看到该值。只有在单击“计算”按钮时才会填充该文本字段,因为您在该按钮上定义了动作侦听器。

如果您需要默认值,例如 10,那么您可以这样做:

 final JTextField  ave1 = new JTextField("10");//or not yet calculated or something on those lines

使用整数参数,java 文档说:

Constructs a new empty <code>TextField</code> with the specified
 * number of columns.
 * A default model is created and the initial string is set to
 * <code>null</code>.
 *
 * @param columns  the number of columns to use to calculate 
 *   the preferred width; if columns is set to zero, the
 *   preferred width will be whatever naturally results from
 *   the component implementation
 */ 

你的问题是这一行。

int i4 = Integer.parseInt(ave1.getText());

据推测,当你点击"Calculate"时,ave1中还没有任何值,所以这一行会抛出异常,它下面的行将永远无法到达。

从您的代码中删除该行,并将单词 int 添加到它下面的行。

int i4 = (i1 + i2 + i3) / 3;

作为一般规则,一个空的 catch 块,例如您正在使用的那个

catch(Exception ex){

}

真是个糟糕的主意;因为这意味着抛出异常时您看不到问题所在。永远不要这样做。