I am a high school student trying to learn java and any help or advice is appreciated. The code does not set the text after I press the button. The actionPerformed does not do what it is supposed to until I change the size of the GUI for some reason. When I run it and press the button a . pops up but nothing else, if you were to run it then you would see what I am talking about. I think it stops during the action performer for some reason but I am really just guessing. Thank you.
import java.awt.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
public class GUI extends JFrame implements ActionListener{
public TextField mpgEnter;
public Label lblResult;
public Button btnEnter;
public TextField gasPriceEnter;
public TextField distanceEnter;
public double mpg;
public double distanceTravel;
double priceOfgas;
public GUI() {
setTitle("GUI Test");
setSize(280, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Label lbl2 = new Label("MPG ||");
add(lbl2);
mpgEnter = new TextField(5);
Label lbl3 = new Label("Price of gas ||");
add(lbl3);
gasPriceEnter = new TextField(5);
Label lbl4 = new Label("Distance");
add(lbl4);
distanceEnter = new TextField(5);
setLayout(new FlowLayout());
add(mpgEnter);
add(gasPriceEnter);
add(distanceEnter);
// add button
btnEnter = new Button("Enter");
btnEnter.addActionListener(this);
add(btnEnter);
//add label
//setResizable(false);
lblResult = new Label("");
add(lblResult);
setVisible(true);
}
public static double calculateGPM(double mpg, double gas,double distance){
double gasPerMile = gas/mpg;
double cost1 = gasPerMile * distance;
NumberFormat formatter = new DecimalFormat("#0.00");
double costFinal = Double.parseDouble(formatter.format(cost1));
return costFinal;
}
@Override
public void actionPerformed(ActionEvent e) {
//System.out.print(test.getText());
mpg = Double.parseDouble(mpgEnter.getText());
priceOfgas= Double.parseDouble(gasPriceEnter.getText());
distanceTravel = Double.parseDouble(distanceEnter.getText());
lblResult.setText("The price for your trip is: $" + calculateGPM(mpg, priceOfgas, distanceTravel));
add(lblResult);
}
}