rounding a number to the hundredth place - java

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

Related

JLabel not appearing on panel

For class I'm supposed to be creating an application that first lets you choose which value you'd like to calculate, then asks to enter the appropriate info. Then when you click "calculate", it SHOULD display the answer. For some reason my JLabel that should be displaying the answer isn't showing up. I've been searching for a solution, but every thing I do, nothing appears after you click "calculate". I am a novice, please help :(
package decay.application;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DecayApplication implements ActionListener {
JFrame frame;
JPanel content;
JLabel prompt1, prompt2, prompt3, prompt4, displayFinal, displayIntitial, displayConstant, choose;
JTextField enterFinal, enterInitial, enterConstant, enterElapsed;
JButton finButton, inButton, conButton, calculate1, calculate2, calculate3;
public DecayApplication(){
frame = new JFrame("Decay Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content = new JPanel();
content.setLayout(new GridLayout(0, 2, 10, 5));
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
choose = new JLabel("Which would you like to calculate?");
content.add(choose);
finButton = new JButton("Final Amount");
finButton.setActionCommand("finalAmount");
finButton.addActionListener(this);
content.add(finButton);
inButton = new JButton("Initial Amount");
inButton.setActionCommand("initialAmount");
inButton.addActionListener(this);
content.add(inButton);
conButton = new JButton("Constant");
conButton.setActionCommand("constant");
conButton.addActionListener(this);
content.add(conButton);
frame.setContentPane(content);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){new DecayApplication();}
public void actionPerformed(ActionEvent event) {
String clicked1 = event.getActionCommand();
String clicked2 = event.getActionCommand();
if (clicked1.equals("finalAmount")) {
prompt1 = new JLabel("Enter the initial amount:");
content.add(prompt1);
enterInitial = new JTextField(10);
content.add(enterInitial);
prompt2 = new JLabel("What's the constant?:");
content.add(prompt2);
enterConstant = new JTextField(10);
content.add(enterConstant);
prompt3 = new JLabel("How many years have elapsed?:");
content.add(prompt3);
enterElapsed = new JTextField(10);
content.add(enterElapsed);
calculate1 = new JButton("Calculate");
calculate1.setActionCommand("Calculate");
calculate1.addActionListener(this);
content.add(calculate1);
displayFinal = new JLabel(" ");
displayFinal.setForeground(Color.red);
content.add(displayFinal);
frame.pack();
if (clicked2.equals("Calculate")){
double finalAmount;
String e1 = enterInitial.getText();
String e2 = enterConstant.getText();
String e3 = enterElapsed.getText();
finalAmount = (Double.parseDouble(e1) + 2.0);
displayFinal.setText(Double.toString(finalAmount));
}
}
}
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
DecayApplication decay = new DecayApplication();
}
}
Here's your method actionPerformed:
public void actionPerformed(ActionEvent event) {
String clicked1 = event.getActionCommand();
String clicked2 = event.getActionCommand();
if (clicked1.equals("finalAmount")) {
prompt1 = new JLabel("Enter the initial amount:");
content.add(prompt1);
enterInitial = new JTextField(10);
content.add(enterInitial);
prompt2 = new JLabel("What's the constant?:");
content.add(prompt2);
enterConstant = new JTextField(10);
content.add(enterConstant);
prompt3 = new JLabel("How many years have elapsed?:");
content.add(prompt3);
enterElapsed = new JTextField(10);
content.add(enterElapsed);
calculate1 = new JButton("Calculate");
calculate1.setActionCommand("Calculate");
calculate1.addActionListener(this);
content.add(calculate1);
displayFinal = new JLabel(" ");
displayFinal.setForeground(Color.red);
content.add(displayFinal);
frame.pack();
//here should the if-loop end, because here is the end of instructions which should be called after clicking on the button
}
//and here the second if-loop
if (clicked2.equals("Calculate")){
double finalAmount;
String e1 = enterInitial.getText();
String e2 = enterConstant.getText();
String e3 = enterElapsed.getText();
finalAmount = (Double.parseDouble(e1) + 2.0);
displayFinal.setText(Double.toString(finalAmount));
}

Java JTexfield Input and Output for Property Tax

I have been trying to run this code which takes the user's assessed home value, the county and school taxes and then outputs them to a text field. This code compiles and runs but there is a logical error somewhere that doesn't let it output any text. I'm just starting with Java so any help would be appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PropertyTax3 extends JFrame
{
// set parameters to define extent of the window
private static final int WIDTH = 500, HEIGHT = 300;
private ExitHandler ebHandler;
private CalculateHandler cbHandler;
private JTextField assessTF, schoolRateTF, countyRateTF, schoolTaxTF, countyTaxTF, totalTaxTF;
public PropertyTax3()
{
// set title, size and visibility aspects of window
setTitle("Calculation of Property Taxes");
//Label Definitions
JLabel assessL = new JLabel("Assesment Home Value:", SwingConstants.RIGHT);
JLabel schoolRateL = new JLabel("Decimal Value of School Tax Rate:", SwingConstants.RIGHT);
JLabel countyRateL = new JLabel("Decimal Value of County Tax Rate:", SwingConstants.RIGHT);
JLabel schoolTaxL = new JLabel("School Taxes:", SwingConstants.RIGHT);
JLabel countyTaxL = new JLabel("County Taxes:", SwingConstants.RIGHT);
JLabel totalTaxL = new JLabel("Total Taxes:", SwingConstants.RIGHT);
//Text Field Definitions
JTextField assessTF = new JTextField(10);
JTextField schoolRateTF = new JTextField(10);
JTextField countyRateTF = new JTextField(10);
JTextField schoolTaxTF = new JTextField(10);
JTextField countyTaxTF = new JTextField(10);
JTextField totalTaxTF = new JTextField(10);
//Exit Button
JButton exit = new JButton("Exit");
ebHandler = new ExitHandler();
exit.addActionListener(ebHandler);
//Calculate Button
JButton calculate = new JButton("Calculate");
cbHandler = new CalculateHandler();
calculate.addActionListener(cbHandler);
//Container format
Container pane = getContentPane();
pane.setLayout(new GridLayout(7,2));
pane.add(assessL);
pane.add(assessTF);
pane.add(schoolRateL);
pane.add(schoolRateTF);
pane.add(countyRateL);
pane.add(countyRateTF);
pane.add(schoolTaxL);
pane.add(schoolTaxTF);
pane.add(countyTaxL);
pane.add(countyTaxTF);
pane.add(totalTaxL);
pane.add(totalTaxTF);
pane.add(exit);
pane.add(calculate);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class ExitHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
private class CalculateHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double countyRate, schoolRate, assessment, schoolTax, countyTax, totalTax;
assessment = Double.parseDouble(assessTF.getText());
schoolRate = Double.parseDouble(schoolRateTF.getText());
countyRate = Double.parseDouble(countyRateTF.getText());
schoolTax = assessment * schoolRate * .01;
countyTax = assessment * countyRate * .01;
totalTax = schoolTax + countyTax;
schoolTaxTF.setText(""+ String.format("%.2f", schoolTax));
countyTaxTF.setText(""+ String.format("%.2f", countyTax));
totalTaxTF.setText(""+ String.format("%.2f", totalTax));
}
}
public static void main(String[] args)
{
// main program to invoke constructor
PropertyTax3 proptax = new PropertyTax3();
}
}
Change this
JTextField assessTF = new JTextField(10);
JTextField schoolRateTF = new JTextField(10);
JTextField countyRateTF = new JTextField(10);
JTextField schoolTaxTF = new JTextField(10);
JTextField countyTaxTF = new JTextField(10);
JTextField totalTaxTF = new JTextField(10);
to this
assessTF = new JTextField(10);
schoolRateTF = new JTextField(10);
countyRateTF = new JTextField(10);
schoolTaxTF = new JTextField(10);
countyTaxTF = new JTextField(10);
totalTaxTF = new JTextField(10);
That way, you aren't using the variables you defined as a class field, but creating new ones. And that's why you couldn't access them later with getText and setText.
That's because there are no values for the program to run with...

Percents calculating part does not work in java

[Now working!] I have this code that should calculate percents (With some GUI). But the calculating part is not working... Maybe some of you know the answer? I think the problem is when I concert it from a string do a double. I'm from Sweden so I have a very crappy english. And all variable names were in swedish so I just translated them with googles translate.
package Java;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class java {
public static void main (String []args){
int frameSizeX = 500;
int frameSizeY = 135;
JPanel p = new JPanel();
p.setPreferredSize( new Dimension(frameSizeX,frameSizeY) );
JFrame f = new JFrame ("Percentage");
f.setSize(frameSizeX,frameSizeY);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.getContentPane().add(p);
JLabel cardiNum = new JLabel ("Cardinal number");
JTextField cardiNumField = new JTextField();
cardiNumField.setPreferredSize( new Dimension( 500, 24 ) );
final String talValue = (cardiNumField.getText());
JLabel perc = new JLabel("Percentage");
JTextField percField = new JTextField();
percField.setPreferredSize( new Dimension( 500, 24 ) );
final String proValue = (percField.getText());
double D = 0;
final JLabel answer = new JLabel("The answer is = " + D);
JButton butt = new JButton("Calculate");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
double A = Double.parseDouble(talValue);
double B = Double.parseDouble(proValue);
double C = A/100;
double D = C*B;
answer.setText("The answer is" + D);
}
});
p.add(cardiNum, BorderLayout.AFTER_LINE_ENDS);
p.add(cardiNumField, BorderLayout.AFTER_LINE_ENDS);
p.add(perc, BorderLayout.AFTER_LINE_ENDS);
p.add(percField, BorderLayout.AFTER_LINE_ENDS);
p.add(butt);
p.add(answer);
f.pack();
f.setVisible(true);
}
}
You're getting the NullPointerException because you need to set those two strings only once the JButton has been clicked, inside the ActionListener.
Put these two lines:
final String talValue = (cardiNumField.getText());
final String proValue = (percField.getText());
inside the ActionListener for the JButton and make the cardiNumField and percField final and it should work. Alternatively, you can just remove those two variables and have:
double A = Double.parseDouble(cardiNumField.getText());
double B = Double.parseDouble(percField.getText());
As Martin Dinov mentions, the problem is that you were reading the contents of the text boxes before the user was able to write in them and click the button. That leads to a NumberFormatException, because you're trying to convert the empty String "" to a double. Therefore, you need to put that code inside the button click event handler. An extra change to fix this is that you need to make your text fields final. i.e.
final JTextField cardiNumField = new JTextField();
final JTextField percField = new JTextField();
That's because the button click handler is an anonymous inner class, so it can only read from final variables.
The following code fixes the problem I think you have been seeing.
public static void main(String[] args) {
int frameSizeX = 500;
int frameSizeY = 135;
JPanel p = new JPanel();
p.setPreferredSize(new Dimension(frameSizeX, frameSizeY));
JFrame f = new JFrame("Percentage");
f.setSize(frameSizeX, frameSizeY);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.getContentPane().add(p);
JLabel cardiNum = new JLabel("Cardinal number");
final JTextField cardiNumField = new JTextField();
cardiNumField.setPreferredSize(new Dimension(500, 24));
JLabel perc = new JLabel("Percentage");
final JTextField percField = new JTextField();
percField.setPreferredSize(new Dimension(500, 24));
double D = 0;
final JLabel answer = new JLabel("The answer is = " + D);
JButton butt = new JButton("Calculate");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
double cardinal = Double.parseDouble(cardiNumField.getText());
double percentage = Double.parseDouble(percField.getText());
double C = cardinal / 100;
double D = C * percentage;
answer.setText("The answer is " + D);
}
});
p.add(cardiNum, BorderLayout.AFTER_LINE_ENDS);
p.add(cardiNumField, BorderLayout.AFTER_LINE_ENDS);
p.add(perc, BorderLayout.AFTER_LINE_ENDS);
p.add(percField, BorderLayout.AFTER_LINE_ENDS);
p.add(butt);
p.add(answer);
f.pack();
f.setVisible(true);
}
Good luck with learning Java. You're obviously very new to it! :)

Empty button listener

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

Trouble with initialization

import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
public class Final extends JFrame
{
private JButton calcButton, exitButton;
private JButton pcalcButton, pexitButton;
private JTextField plength, pwidth, pdepth, pvolume;
private JTextField hlength, hwidth, hdepth, hvolume;
private JLabel lengthLabel, widthLabel, depthLabel, volumeLabel;
private JRadioButton roundrButton, ovalrButton;
public Final()
{
super( "Final" );
JTabbedPane tab = new JTabbedPane();
// constructing the first panel
JPanel p1 = new JPanel(new GridLayout(5,1));
pcalcButton = new JButton("Calculate Volume");
pexitButton = new JButton("Exit");
plength = new JTextField(5);
pwidth = new JTextField(5);
pdepth = new JTextField(5);
pvolume = new JTextField(5);
lengthLabel = new JLabel("Enter the pool's length (ft):");
widthLabel = new JLabel("Enter the pool's width (ft):");
depthLabel = new JLabel("Enter the pool's depth (ft):");
volumeLabel = new JLabel("The pool's volume (ft^3):");
p1.add(lengthLabel);
p1.add(plength);
p1.add(widthLabel);
p1.add(pwidth);
p1.add(depthLabel);
p1.add(pdepth);
p1.add(volumeLabel);
p1.add(pvolume);
p1.add(pcalcButton);
p1.add(pexitButton);
tab.addTab( "Pools", null, p1, " Panel #1" );
calcButtonHandler chandler =new calcButtonHandler();
pcalcButton.addActionListener(chandler);
exitButtonHandler ehandler =new exitButtonHandler();
pexitButton.addActionListener(ehandler);
FocusHandler fhandler =new FocusHandler();
plength.addFocusListener(fhandler);
pwidth.addFocusListener(fhandler);
pdepth.addFocusListener(fhandler);
pvolume.addFocusListener(fhandler);
// constructing the second panel
JPanel p2 = new JPanel(new GridLayout(6,1));
ButtonGroup tubtype = new ButtonGroup();
roundrButton = new JRadioButton("Round", true);
roundrButton.setActionCommand("round");
tubtype.add(roundrButton);
ovalrButton = new JRadioButton("Oval", false);
ovalrButton.setActionCommand("oval");
tubtype.add(ovalrButton);
calcButton = new JButton("Calculate Volume");
exitButton = new JButton("Exit");
hlength = new JTextField(5);
hwidth = new JTextField(5);
hdepth = new JTextField(5);
hvolume = new JTextField(5);
lengthLabel = new JLabel("Enter the tub's length (ft):");
widthLabel = new JLabel("Enter the tub's width (ft):");
depthLabel = new JLabel("Enter the tub's depth (ft):");
volumeLabel = new JLabel("The tub's volume (ft^3):");
p2.add(roundrButton);
p2.add(ovalrButton);
p2.add(lengthLabel);
p2.add(hlength);
p2.add(widthLabel);
p2.add(hwidth);
p2.add(depthLabel);
p2.add(hdepth);
p2.add(volumeLabel);
p2.add(hvolume);
p2.add(calcButton);
p2.add(exitButton);
tab.addTab( "Hot Tubs", null, p2, " Panel #1" );
calcButtonHandler2 ihandler =new calcButtonHandler2();
calcButton.addActionListener(ihandler);
exitButtonHandler ghandler =new exitButtonHandler();
exitButton.addActionListener(ghandler);
FocusHandler hhandler =new FocusHandler();
hlength.addFocusListener(hhandler);
hwidth.addFocusListener(hhandler);
hdepth.addFocusListener(hhandler);
hvolume.addFocusListener(hhandler);
// add JTabbedPane to container
getContentPane().add( tab );
setSize( 550, 500 );
setVisible( true );
}
public class calcButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
DecimalFormat num =new DecimalFormat(",###.##");
double sLength, sWidth, sdepth, Total;
sLength = Double.parseDouble(plength.getText());
sWidth = Double.parseDouble(pwidth.getText());
sdepth = Double.parseDouble(pdepth.getText());
if(e.getSource() == pcalcButton) {
Total = sLength * sWidth * sdepth;
pvolume.setText(num.format(Total));
try{
String value=pvolume.getText();
File file = new File("output.txt");
FileWriter fstream = new FileWriter(file,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Length= "+sLength+", Width= "+sWidth+", Depth= "+sdepth+" so the volume of Swimming Pool is "+value);
out.newLine();
out.close();
}
catch(Exception ex){}
}
}
}
public class calcButtonHandler2 implements ActionListener {
public void actionPerformed(ActionEvent g) {
DecimalFormat num =new DecimalFormat(",###.##");
double cLength, cWidth, cdepth, Total;
cLength = Double.parseDouble(hlength.getText());
cWidth = Double.parseDouble(hwidth.getText());
cdepth = Double.parseDouble(hdepth.getText());
try
{
if(roundrButton.isSelected())//**roundrButton cannot be resolved
{
Total = Math.PI * Math.pow(cLength / 2.0, 2) * cdepth;
}
else
{
Total = Math.PI * Math.pow(cLength * cWidth, 2) * cdepth;
}
hvolume.setText(""+num.format(Total));
}
catch(Exception ex){}
}
}
}
public class exitButtonHandler implements ActionListener { //**The public type exitButtonHandler must be defined in its own file
public void actionPerformed(ActionEvent g){
System.exit(0);
}
}
public class FocusHandler implements FocusListener { //**The public type FocusHandler must be defined in its own file
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
}
public static void main( String args[] )
{
Final tabs = new Final();
tabs.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
I am getting 3 errors, denoted by the //** next to the lines. Please help me to figure out the problems I am having.
Change calcButtonHandler2 definition to accept a reference to roundButton from where it's defined.
public class calcButtonHandler2 implements ActionListener {
private final JRadioButton roundrButton;
public calcButtonHandler(JRadioButton roundrButton)
{
this.roundrButton= roundrButton;
}
....
}
and pass in the reference when you create an instance of calcButtonHandler2
calcButtonHandler chandler =new calcButtonHandler(roundrButton);
And as for the last two error, move the class declarations to separate files as called out by the compilation error or remove the public keyword from their definitions (I would recommend the first method).
First of all write all the classes in their separate .java files.
The JRadioButton roundrButton is declared in the class Final so it cannot be accessed from another class calcButtonHandler2 directly.
You need to use an object of the class Final to access it or you can make use of inner classes to access it.

Categories

Resources