Integer won't appear in a TextField

jhenryj09

I have a problem with my program. I'm trying to put an integer in a textfield. This is my code:

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

}

I'm trying have ave1.setText(String.valueOf(i4)); appear in a textfield but it won't.
What am I doing wrong?

Dawood ibn Kareem

Your problem is this line.

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

Presumably, when you click "Calculate", there's no value in ave1 yet, so this line will throw an exception, and the line below it will never be reached.

Remove that line from your code, and add the word int to the line below it.

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

As a general rule, an empty catch block such as the one you're using

catch(Exception ex){

}

is a REALLY TERRIBLE idea; because it means you don't see what the problem is when an exception is thrown. Never do this.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事