Java JTexfield Input and Output for Property Tax - java

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...

Related

StackOverflowError when adding JTextField to the constructor

So I do know what an StackOverflowError is, the problem however is I can't find it here. I am supposed to make a simple GUI with labels, text fields and buttons. One of these buttons is supposed to "clear" the text fields, so I add that by putting text field as an argument in the constructor, but when I actually add the text fields i just get an stack overflow error. Here is the code:
Orders class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Orders extends JFrame {
public Orders() {
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(4, 2, 2, 2));
JLabel name = new JLabel("Item name:");
JLabel number = new JLabel("Number of:");
JLabel cost = new JLabel("Cost:");
JLabel amount = new JLabel("Amount owed:");
JTextField nameJtf = new JTextField(10);
JTextField numberJtf = new JTextField(10);
JTextField costJtf = new JTextField(10);
JTextField amountJtf = new JTextField(10);
panel1.add(name);
panel1.add(nameJtf);
panel1.add(number);
panel1.add(numberJtf);
panel1.add(cost);
panel1.add(costJtf);
panel1.add(amount);
panel1.add(amountJtf);
JPanel panel2 = new JPanel();
JButton calculate = new JButton("Calculate");
JButton save = new JButton("Save");
JButton clear = new JButton("Clear");
JButton exit = new JButton("Exit");
panel2.add(calculate);
panel2.add(save);
panel2.add(clear);
panel2.add(exit);
OnClick action = new OnClick(exit, clear, save, calculate, nameJtf, numberJtf, costJtf, amountJtf);
exit.addActionListener(action);
this.setTitle("Otto's Items Orders Calculator");
this.add(panel1, BorderLayout.NORTH);
this.add(panel2, BorderLayout.SOUTH);
this.setSize(400, 200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new Orders();
}
}
OnClick class :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OnClick extends Orders implements ActionListener {
private JButton exitModify = null;
private JButton clearModify = null;
private JButton saveModify = null;
private JButton calculateModify = null;
private JTextField nameModify = null;
private JTextField numberModify = null;
private JTextField costModify = null;
private JTextField amountModify = null;
public OnClick (JButton _exitModify, JButton _clearModify, JButton _saveModify, JButton _calculateModify, JTextField _nameModify, JTextField _numberModify, JTextField _costModify, JTextField _amountModify) {
exitModify = _exitModify;
clearModify = _clearModify;
saveModify = _saveModify;
calculateModify = _calculateModify;
nameModify = _nameModify;
numberModify = _numberModify;
costModify = _numberModify;
amountModify = _amountModify;
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == this.exitModify) {
System.exit(0);
} else if (o == this.clearModify) {
amountModify = null;
nameModify = null;
costModify = null;
numberModify = null;
}
}
}
As soon as I add nameJtf I get this error.

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

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

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

Categories

Resources