Empty button listener - java

I've only been working with Java for about a year now and have just gotten into the basics of GUI. I'm writing a program that will calculate the center of mass between 2, 3, 4, or 5 points (user's option). Depending on the number of points the user wants to enter, a number of editable JTextFields appear to get input for coordinates and masses of those coordinates. Unfortunately, when asked to calculate the center of mass, the button won't display what I want. The way it's written now is the only way I've gotten it to compile/run without an empty string error. I believe it has to do with how I've initialized the variables/where they're initialized between constructors, but I can't for the life of me figure out where that problem lies exactly. Any help will be greatly appreciated! I've attached the code - I know it's long, but you never know what can be useful. Thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class ComboBox extends JFrame
/*************VARIABLES*******************************************************/
{
private final int WIDTH = 1500;
private final int HEIGHT = 1500;
private JPanel northPanel;
private JPanel centerPanel;
private JPanel blankPanel;
private JPanel pointsPanel;
private JPanel selectedPointsPanel;
private JComboBox pointsBox;
private JTextField selectedPoints;
private JLabel selection;
private String choose = "Choose an option...";
private String twoPoints = "2 points";
private String threePoints = "3 points";
private String fourPoints = "4 points";
private String fivePoints = "5 points";
private String[] points = {choose, twoPoints, threePoints, fourPoints, fivePoints};
private JPanel coordinatesPanel;
private JPanel cPanel;
private JTextField xField1;
private JTextField xField2;
private JTextField xField3;
private JTextField xField4;
private JTextField xField5;
private JTextField yField1;
private JTextField yField2;
private JTextField yField3;
private JTextField yField4;
private JTextField yField5;
private JLabel instructions;
private JLabel X;
private JLabel Y;
private JLabel blankLabel;
private JPanel massPanel;
private JTextField mass1 = new JTextField(10);
private JTextField mass2 = new JTextField(10);
private JTextField mass3 = new JTextField(10);
private JTextField mass4 = new JTextField(10);
private JTextField mass5 = new JTextField(10);
private JLabel instructions2;
Boolean calcBool = false;
private JButton calcButton = new JButton("Calculate");
private JButton resetButton = new JButton("Reset");
private JPanel displayPanel;
private double centerX;
private double centerY;
private JLabel display;
private double x1, x2, x3, x4, x5;
private double y1, y2, y3, y4, y5;
private double m1, m2, m3, m4, m5;
/**********************************WINDOW************************************/
public ComboBox()
{
super("Choose an option");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3,2));
setLocationRelativeTo(null);
setResizable(true);
setSize(WIDTH, HEIGHT);
buildPointsPanel();
buildCoordinatesPanel();
buildMassPanel();
buildDisplayPanel();
buildBlankPanel();
add(pointsPanel);
add(coordinatesPanel);
add(massPanel);
add(blankPanel);
add(calcButton);
add(blankPanel);
add(resetButton);
add(blankPanel);
add(displayPanel);
calcButton.addActionListener(new CalcButtonListener());
pointsBox.addActionListener(new ComboBoxListener());
//resetButton.addActionListener(new ResetButtonListener());
pack();
setVisible(true);
}
/************************BUILD ALL THE PANELS**********************/
private void buildBlankPanel()
{
blankPanel = new JPanel();
}
private void buildPointsPanel()
{
pointsPanel = new JPanel();
pointsPanel.setLayout(new GridLayout(3,1));
pointsBox = new JComboBox(points);
pointsBox.addActionListener(new ComboBoxListener());
pointsPanel.add(pointsBox);
selection = new JLabel("You selected: ");
selectedPoints = new JTextField(10);
selectedPoints.setEditable(false);
pointsPanel.add(selection);
pointsPanel.add(selectedPoints);
}
private void buildCoordinatesPanel()
{
coordinatesPanel = new JPanel();
coordinatesPanel.setLayout(new GridLayout(6,2));
instructions = new JLabel("Please enter the X and Y values of your points below.");
JLabel blank = new JLabel("");
X = new JLabel("X values");
Y = new JLabel("Y values");
blankLabel = new JLabel("");
coordinatesPanel.add(instructions);
coordinatesPanel.add(blankLabel);
coordinatesPanel.add(X);
coordinatesPanel.add(Y);
xField1 = new JTextField(10);
xField1.setEditable(true);
yField1 = new JTextField(10);
yField1.setEditable(true);
xField2 = new JTextField(10);
xField2.setEditable(true);
yField2 = new JTextField(10);
yField2.setEditable(true);
xField3 = new JTextField(10);
xField3.setEditable(true);
yField3 = new JTextField(10);
yField3.setEditable(true);
xField4 = new JTextField(10);
xField4.setEditable(true);
yField4 = new JTextField(10);
yField4.setEditable(true);
xField5 = new JTextField(10);
xField5.setEditable(true);
yField5 = new JTextField(10);
yField5.setEditable(true);
}
private void buildMassPanel()
{
massPanel = new JPanel();
instructions2 = new JLabel("Please enter the masses of your points");
massPanel.add(instructions2);
mass1.setEditable(true);
mass2.setEditable(true);
mass3.setEditable(true);
mass4.setEditable(true);
mass5.setEditable(true);
}
private void buildDisplayPanel()
{
displayPanel = new JPanel();
//display = new JLabel("The center of mass is located at (" + centerX + "," + centerY
+").");
//displayPanel.add(display);
}
/********************************COMBOBOX LISTENER****************************/
private class ComboBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{ //The following asks the user to select the number of points they want and stores
it
String select =(String) pointsBox.getSelectedItem();
selectedPoints.setText(select);
//The following determines how many text fields to display depending on how many
points the user wants
if (select==twoPoints)
{
coordinatesPanel.add(xField1);
coordinatesPanel.add(yField1);
coordinatesPanel.add(xField2);
coordinatesPanel.add(yField2);
massPanel.add(mass1);
massPanel.add(mass2);
centerX = ((m1*x1)+(m2*x2)/(m1+m2));
centerY = ((m1*y1)+(m2*y2)/(m1+m2));
}
if (select==threePoints)
{
coordinatesPanel.add(xField1);
coordinatesPanel.add(yField1);
coordinatesPanel.add(xField2);
coordinatesPanel.add(yField2);
coordinatesPanel.add(xField3);
coordinatesPanel.add(yField3);
massPanel.add(mass1);
massPanel.add(mass2);
massPanel.add(mass3);
centerX = ((m1*x1)+(m2*x2)+(m3*x3)/(m1+m2+m3));
centerY = ((m1*y1)+(m2*y2)+(m3*y3)/(m1+m2+m3));
}
if (select==fourPoints)
{
coordinatesPanel.add(xField1);
coordinatesPanel.add(yField1);
coordinatesPanel.add(xField2);
coordinatesPanel.add(yField2);
coordinatesPanel.add(xField3);
coordinatesPanel.add(yField3);
coordinatesPanel.add(xField4);
coordinatesPanel.add(yField4);
massPanel.add(mass1);
massPanel.add(mass2);
massPanel.add(mass3);
massPanel.add(mass4);
centerX = ((m1*x1)+(m2*x2)+(m3*x3)+(m4*x4)/(m1+m2+m3+m4));
centerY = ((m1*y1)+(m2*y2)+(m3*y3)+(m4*y4)/(m1+m2+m3+m4));
}
if (select==fivePoints)
{
coordinatesPanel.add(xField1);
coordinatesPanel.add(yField1);
coordinatesPanel.add(xField2);
coordinatesPanel.add(yField2);
coordinatesPanel.add(xField3);
coordinatesPanel.add(yField3);
coordinatesPanel.add(xField4);
coordinatesPanel.add(yField4);
coordinatesPanel.add(xField5);
coordinatesPanel.add(yField5);
massPanel.add(mass1);
massPanel.add(mass2);
massPanel.add(mass3);
massPanel.add(mass4);
massPanel.add(mass5);
centerX = ((m1*x1)+(m2*x2)+(m3*x3)+(m4*x4)+(m5*x5)/(m1+m2+m3+m4+m5));
centerY = ((m1*y1)+(m2*y2)+(m3*y3)+(m4*y4)+(m5*y5)/(m1+m2+m3+m4+m5));
}
if (select==choose)
{
JOptionPane.showMessageDialog(null, "Please select a valid option");
}
}
}
/********************************CALC BUTTON LISTENER******************************/
private class CalcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
display = new JLabel("The center of mass is located at (" + centerX + "," + centerY
+").");
displayPanel.add(display);
}
}
/******************************MAIN METHOD***************************/
public static void main(String[] args)
{
new ComboBox();
}

What you should do is instantiate the display, where you have it declared.
JLabel display = new JLabel(" ");
Then add it to the GUI, wherever in the code you're adding all the other components. Than in your listener class, just set the text
public void actionPerformed(ActionEvent e){
display.setText("some text");
}
The way you're doing it might mess up your desired GUI formatting. If you were to do it though, you need to revalidate() and repaint() after adding any new components. I'd recommend using the former.

Don't know where is your specific problem, but looking at your code i see some potential bugs. In java you compare objects equality with equals() not with == .== is just for references.
So changes all lines where you compare Strings with == replace with equals.
For example change
select==fivePoints
to
select.equals(fivePoints)
Having attributes like
private JTextField mass1 = new JTextField(10);
private JTextField mass2 = new JTextField(10);
private JTextField mass3 = new JTextField(10);
private JTextField mass4 = new JTextField(10);
private JTextField mass5 = new JTextField(10);
is not the best way, you can store them in a Collection or in array.
private List<JTextField> masses;
Always when you add a component call revalidate and repaint.
display = new JLabel("The center of mass is located at (" + centerX + "," + centerY
+").");
displayPanel.add(display);
displayPanel.revalidate();
displayPanel.repaint();

Related

Error in Tax Return GUI

I've been trying to make this Tax Return Program to work but im having some difficulties. It runs sure, but the "Calculation Button" does not work.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Tax extends JFrame
{
private int NewNetPay = 0;
private JPanel panelN;
private JPanel panelS;
private JPanel panelE;
private JPanel panelW;
private JPanel panelC;
private JButton calcButton;
private JButton resetButton;
private JButton exitButton;
private JRadioButton hohRB;
private JRadioButton marriedJRB;
private JRadioButton marriedSRB;
private JRadioButton singleRB;
private JCheckBox mortgageCB;
private JCheckBox charitableCB;
private JCheckBox childCB;
private JCheckBox educationCB;
private JTextField childTF;
private JTextField mortgageTF;
private JTextField charitableTF;
private JTextField educationTF;
private JLabel firstName;
private JTextField name1TF;
private JLabel lastName;
private JTextField name2TF;
private JLabel gross;
private JTextField grossTF;
private JLabel netPay;
private JTextField netPayTF;
final int WIN_WIDTH = 500;
final int WIN_HEIGHT = 300;
public static void main (String[] args)
{
new Tax();
}
public Tax()
{
setTitle("CSC142 Tax Calculator");
setSize(WIN_WIDTH,WIN_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(20, 20));
buildPanel();
//add(panel);
setVisible(true);
}
private void buildPanel()
{
JFrame frame = new JFrame();
hohRB = new JRadioButton("Head of Household");
marriedJRB = new JRadioButton("Married, Jointly");
marriedSRB = new JRadioButton("Married, Seperately");
singleRB = new JRadioButton("Single");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(hohRB);
radioGroup.add(marriedJRB);
radioGroup.add(marriedSRB);
radioGroup.add(singleRB);
mortgageCB = new JCheckBox("Mortgage");
charitableCB = new JCheckBox("Charitable Donation");
childCB = new JCheckBox("Child Deduction");
educationCB = new JCheckBox("Education Expenses");
ButtonGroup checkGroup = new ButtonGroup();
checkGroup.add(mortgageCB);
checkGroup.add(charitableCB);
checkGroup.add(childCB);
checkGroup.add(educationCB);
calcButton = new JButton(" Calculate Taxes ");
resetButton = new JButton(" Reset Values ");
exitButton = new JButton (" Exit Application ");
panelN = new JPanel();
panelS = new JPanel();
panelE = new JPanel();
panelW = new JPanel();
panelC = new JPanel();
add(panelN, BorderLayout.NORTH);
add(panelS, BorderLayout.SOUTH);
add(panelE, BorderLayout.EAST);
add(panelW, BorderLayout.WEST);
add(panelC, BorderLayout.CENTER);
panelN.setLayout(new BoxLayout(panelN, BoxLayout.X_AXIS));
panelS.setLayout(new BoxLayout(panelS, BoxLayout.X_AXIS));
panelE.setLayout(new BoxLayout(panelE, BoxLayout.Y_AXIS));
panelW.setLayout(new BoxLayout(panelW, BoxLayout.Y_AXIS));
panelC.setLayout(new BoxLayout(panelC, BoxLayout.Y_AXIS));
panelW.add(hohRB);
panelW.add(marriedJRB);
panelW.add(marriedSRB);
panelW.add(singleRB);
JTextField childTF = new JTextField();
childTF.setPreferredSize( new Dimension (10,10));
JTextField mortgageTF = new JTextField();
mortgageTF.setPreferredSize( new Dimension (10,10));
JTextField charitableTF = new JTextField();
charitableTF.setPreferredSize( new Dimension (10,10));
JTextField educationTF = new JTextField();
educationTF.setPreferredSize( new Dimension (10,10));
childTF.setEnabled(false);
mortgageTF.setEnabled(false);
charitableTF.setEnabled(false);
educationTF.setEnabled(false);
panelC.add(mortgageCB);
panelC.add(mortgageTF);
panelC.add(charitableCB);
panelC.add(charitableTF);
panelC.add(childCB);
panelC.add(childTF);
panelC.add(educationCB);
panelC.add(educationTF);
panelS.add(Box.createRigidArea(new Dimension(35,0)));
panelS.add(calcButton);
panelS.add(Box.createRigidArea(new Dimension(20,0)));
panelS.add(resetButton);
panelS.add(Box.createRigidArea(new Dimension(20,0)));
panelS.add(exitButton);
panelW.setBorder(BorderFactory.createTitledBorder("Filing Status"));
panelC.setBorder(BorderFactory.createTitledBorder("Deductions"));
JTextField name1TF = new JTextField();
JTextField name2TF = new JTextField();
JTextField grossTF = new JTextField();
JLabel firstName = new JLabel(" First Name ");
JLabel lastName = new JLabel(" Last Name ");
JLabel gross = new JLabel(" Gross Income ");
panelN.add(firstName);
panelN.add(name1TF);
panelN.add(lastName);
panelN.add(name2TF);
panelN.add(gross);
panelN.add(grossTF);
JLabel netPay = new JLabel("Net Pay");
JTextField netPayTF = new JTextField(1);
panelE.add(netPay);
panelE.add(netPayTF);
calcButton.addActionListener(new CalcButtonListener());
}
private class CalcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inputo;
inputo = grossTF.getText();
if (mortgageCB.isSelected())
NewNetPay = Integer.parseInt(inputo) - 10000;
else if (charitableCB.isSelected())
NewNetPay = Integer.parseInt(inputo) - 5000 ;
else if (childCB.isSelected())
NewNetPay = Integer.parseInt(inputo) - 1000;
else if (educationCB.isSelected())
NewNetPay = Integer.parseInt(inputo) - 20000;
netPayTF.setText(" " + NewNetPay);
}
}
} `enter code here`
I am trying to make it so that a user enters a salary in the gross income text field, then depending on what checkbox they click they will get a deduction. Then finally, the amount will be displayed in the net pay text field.
You are adding JTextField grossTF = new JTextField(); where grossTF is a local Variable to the frame, and trying to get data from inputo = grossTF.getText(); where this.grossTF which is a class member that would be initialized null when getting the data, hence you'd get a NPE.
Also you've done the same for netPayTF, change them to..
netPayTF = new JTextField(1); & grossTF = new JTextField();

Why is setText of JTextField not working in the actionPerformed method?

im making a currency calculator and i have an issue with not being able to set the result of the calculation into the result JTextField, which is the object otherTextField.
Here is my class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ValutaKalkulator implements ActionListener {
private double nokValue;
private double otherValue;
private JButton buttonRemoveNok;
private JButton removeOther;
private JButton removeBoth;
private JButton exitButton;
private JButton usdButton;
private JButton sekButton;
private JButton gbpButton;
private JButton eurButton;
private JLabel nokLabel;
private JTextField nokTextField;
private JLabel otherLabel;
private JTextField otherTextField;
public ValutaKalkulator()
{
JFrame frame = new JFrame();
frame.setTitle("VALUTAKALKULATOR");
buttonRemoveNok = new JButton("Fjern NOK");
removeOther = new JButton("Fjern annen valuta");
removeBoth = new JButton("Fjern begge");
exitButton = new JButton("Avslutt");
usdButton = new JButton("USD");
sekButton = new JButton("SEK");
gbpButton = new JButton("GBP");
eurButton = new JButton("EUR");
nokLabel = new JLabel("NOK");
JTextField nokTextField = new JTextField();
otherLabel = new JLabel("Annen valuta");
otherTextField = new JTextField();
buttonRemoveNok.addActionListener(this);
removeOther.addActionListener(this);
removeBoth.addActionListener(this);
exitButton.addActionListener(this);
usdButton.addActionListener(this);
sekButton.addActionListener(this);
gbpButton.addActionListener(this);
eurButton.addActionListener(this);
JPanel pnlSouth = new JPanel(new GridLayout(1, 4));
JPanel pnlCenter = new JPanel(new GridLayout(2, 2));
JPanel pnlNorth = new JPanel(new GridLayout(1, 4));
pnlNorth.add(nokLabel);
pnlNorth.add(nokTextField);
pnlNorth.add(otherLabel);
pnlNorth.add(otherTextField);
pnlCenter.add(gbpButton);
pnlCenter.add(eurButton);
pnlCenter.add(usdButton);
pnlCenter.add(sekButton);
pnlSouth.add(buttonRemoveNok);
pnlSouth.add(removeOther);
pnlSouth.add(removeBoth);
pnlSouth.add(exitButton);
frame.add(pnlNorth, BorderLayout.NORTH);
frame.add(pnlSouth, BorderLayout.SOUTH);
frame.add(pnlCenter, BorderLayout.CENTER);
frame.setVisible(true);
frame.pack();
}
public String calculateFromNok(String nokValueString, String toValue)
{
double result = 0;
double nokValue = Double.valueOf(nokValueString);
switch(toValue)
{
case "GBP":
result = nokValue * 10.8980 / 100;
break;
case "EUR":
result = nokValue * 9.2450 / 100;
break;
case "USD":
result = nokValue * 8.5223 / 100;
break;
case "SEK":
result = nokValue * 96.48 / 100;
break;
}
String resultString = Double.toString(result);
return resultString;
}
public void actionPerformed(ActionEvent event)
{
String text = event.getActionCommand();
switch(text)
{
case "USD":
String txt = nokTextField.getText();
String txt2 = calculateFromNok(txt, "USD");
otherTextField.setText(txt2);
break;
}
}
}
I know the currencies are not correct and there are other logical flaws and bad variable names, but my question for now is why can i not put the result from the method calculateFromNok into my JTextField otherTextField?
Help appreciated thx!
You are creating an initialize local variable JTextField nokTextField.
So private JTextField nokTextField; is not initializing. That's why it's giving you nullpointerexception.
Just Change At Line Number 37:
JTextField nokTextField = new JTextField();
To
nokTextField = new JTextField();
Your issue is with the line:
JTextField nokTextField = new JTextField();
Change it to:
nokTextField = new JTextField();
The reason this happens is that you previously defined nokTextField at the top, and then you initialized a separate variable with the same name in the constructor. Using an IDE such as Eclipse makes these types of errors very easy to catch. I suggest you use one.

How do I Assign an Array to the Combo Boxes

In order to make the program work I need to have a drop down menu (combo box) that shows all of the possible units to convert to for Stoichiometry.
I know that you must assign an array to a combo box, but I am not sure how. If somebody could help it would be great.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Conversion extends JFrame
{
private JLabel molarMass1;
private JLabel molarMass2;
private JLabel moles1;
private JLabel moles2;
private JLabel amount1;
private JLabel amount2;
private JTextField M1M2;
private JTextField M2M1;
private JTextField moles1moles2;
private JTextField moles2moles1;
private JTextField amount1amount2;
private JTextField amount2amount1;
private JComboBox UnitsOne;
private JComboBox UnitsTwo;
private static final int WIDTH = 500;
private static final int HEIGHT = 50;
Conversion()
{}
public void burst()
{
setTitle("Stoichiometry");
Container z = getContentPane();
z.setLayout(new GridLayout(1, 4));
molarMass1 = new JLabel("Molar Mass 1: ", SwingConstants.LEFT);
molarMass2 = new JLabel("Molar Mass 2: ", SwingConstants.RIGHT);
moles1 = new JLabel("Number of Moles 1: ", SwingConstants.LEFT);
moles2 = new JLabel("Number of Moles 2: ", SwingConstants.RIGHT);
amount1 = new JLabel("Amount of substance 1: ", SwingConstants.LEFT);
amount2 = new JLabel("Amount of substance 2: ", SwingConstants.RIGHT);
M1M2 = new JTextField(7);
M2M1 = new JTextField(7);
moles1moles2 = new JTextField(6);
moles2moles1 = new JTextField(6);
amount1amount2 = new JTextField(5);
amount2amount1 = new JTextField(5);
UnitsOne = new JComboBox(10);
UnitsTwo = new JComboBox(10);
z.add(molarMass1);
z.add(M1M2);
z.add(molarMass2);
z.add(M2M1);
z.add(moles1);
z.add(moles1moles2);
z.add(moles2);
z.add(moles2moles1);
z.add(amount1);
z.add(amount1amount2);
z.add(amount2);
z.add(amount2amount1);
z.add(UnitsOne);
z.add(UnitsTwo);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
}
I don't see where the array you want to assign to the combo box is in your code, but there is a constructor which do exactly what you need: http://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html#JComboBox(E[])
Alternatively you can add items to the JComboBox later using the addItem() method
Also have a look here: https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html

rounding a number to the hundredth place

I want to round the output to the hundredth place but have failed to do so.
Here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Assignment2Part2 extends JFrame{
//window
private static final int WIDTH = 550;
private static final int HEIGHT = 400;
private JLabel firstNameL, lastNameL, milesL, costL, mpgL, dailycostL;//labels for all the variables
private JTextField firstNameTF, lastNameTF, milesTF, costTF, mpgTF, dailycostTF;//text fields for all the variables
private JButton calculateB, exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public Assignment2Part2 ()
{
setTitle("Find your daily cost of driving");
//labels
firstNameL = new JLabel("First Name ", SwingConstants.CENTER);
lastNameL = new JLabel("Last Name ",SwingConstants.CENTER);
milesL = new JLabel("Total miles driven per day ",SwingConstants.CENTER);
costL = new JLabel("Cost per gallon of gas ",SwingConstants.CENTER);
mpgL = new JLabel("Average MPG ",SwingConstants.CENTER);
dailycostL = new JLabel("Daily cost of driving is: ",SwingConstants.CENTER);
//text fields
firstNameTF = new JTextField();
lastNameTF = new JTextField();
milesTF = new JTextField();
costTF = new JTextField();
mpgTF = new JTextField();
dailycostTF = new JTextField();
//find button
calculateB = new JButton("Find");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
//exit button
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
Container pane = getContentPane();
pane.setLayout(new GridLayout(8, 4));
//panes
pane.add(firstNameL);
pane.add(firstNameTF);
pane.add(lastNameL);
pane.add(lastNameTF);
pane.add(milesL);
pane.add(milesTF);
pane.add(costL);
pane.add(costTF);
pane.add(mpgL);
pane.add(mpgTF);
pane.add(dailycostL);
pane.add(dailycostTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
//find button
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//variables
double first, last, total, cost, averagempg, dailycost;
//strings to doubles
total = Double.parseDouble(milesTF.getText());
cost = Double.parseDouble(costTF.getText());
averagempg = Double.parseDouble(mpgTF.getText());
//calculates cost
dailycost = (total * cost)/averagempg;
//outputs text
dailycostTF.setText("$" + dailycost);
}
}
//exit button
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
public static void main(String[] args){
Assignment2Part2 rectObject = new Assignment2Part2();
}
}
the output line being
dailycostTF.setText("$" + dailycost);
Any help would be great! I am completely new to Java.
An easy way is to use either the number format or decimal format class.
NumberFormat dollars = new NumberFormat.getCurrencyInstance();
Then you can format numbers into dollars quite easily. No clunky "$" needed.
DecimalFormat df = new DecimalFormat("#.##");
dailyCost = Double.valueOf(df.format(dailyCost));

Java GUI won't display a prompt I want it to

So my program is designed to take in 2 values, make a calculation, and give this calculations value. I want to display it as a prompt in the GUI in the actionPerformed section after the button is clicked. It looks like it should show up but I can't seem to find why it isn't? It's "prompt2" that isn't showing up. Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Windchill extends JFrame implements ActionListener{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private String degree;
private String wind;
private int degreeInt;
private int windInt;
private double windChillInt;
private JButton windButton;
private JLabel prompt;
private JLabel prompt1;
private JLabel prompt2;
private JTextField inputLine;
private JTextField inputLine1;
public Windchill(){
setTitle("Windchill");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
inputLine = new JTextField();
inputLine.setColumns(3);
inputLine.addActionListener(this);
contentPane.add(inputLine);
prompt = new JLabel();
prompt.setText("Enter the degrees in Farienheight ");
prompt.setSize(150,25);
contentPane.add(prompt);
inputLine1 = new JTextField();
inputLine1.setColumns(3);
inputLine1.addActionListener(this);
contentPane.add(inputLine1);
prompt1 = new JLabel();
prompt1.setText("Enter the wind speed in MPH");
prompt1.setSize(150,25);
contentPane.add(prompt1);
windButton = new JButton("Calculate windchill");
contentPane.add(windButton);
windButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() instanceof JButton){
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == windButton){
degree = inputLine.getText();
degreeInt = Integer.parseInt(degree);
wind = inputLine1.getText();
windInt = Integer.parseInt(wind);
windChillInt = 0.08 * (degreeInt - 91.4)*(3.71* (Math.sqrt(windInt)) + 5.81 - 0.25 *windInt) + 91.4;
prompt2 = new JLabel();
prompt2.setText("The windchill is " + windChillInt);
prompt2.setSize(150,25);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(prompt2);
}
}
}
public static void main(String[] args) {
Windchill frame;
frame = new Windchill();
frame.setVisible(true);
}
}
prompt2 isn't showing up as Swing containers need to be validated for any newly added components can be visible. Also it's good practice to repaint. You could do:
contentPane.revalidate();
contentPane.repaint();
Side Notes:
It is unnecessary to set the layout again for the your ActionListener
contentPane.add(prompt2) can be simplified to add(prompt2)
Alternatively, you could just add the prompt2 JLabel to the contentPane on startup with empty String content and call setText to update.

Categories

Resources