簡體   English   中英

整數不會出現在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)); 出現在文本字段中,但不會。
我究竟做錯了什么?

您的問題是這條線。

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

大概,當您單擊“計算”時, ave1還沒有任何值,因此此行將引發異常,並且永遠不會到達其下方的行。

從代碼中刪除該行,然后將int單詞添加到其下面的行中。

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

通常,空的catch塊(例如您正在使用的塊)

catch(Exception ex){

}

是一個非常可怕的主意; 因為這意味着拋出異常時您看不到問題出在哪里。 永遠不要這樣做。

僅在單擊“計算”按鈕時,您才會在文本字段中看到該值。 僅當您單擊“計算”按鈕時才填充該文本字段,因為您在該按鈕上定義了動作偵聽器。

如果您需要默認值,請說10,那么您可以執行以下操作:

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

使用整數參數,java doc說:

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
 */ 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM