Java Tax Calculator Jtextfield must replace if user inputs $ commas % spaces - java

I need to replace spaces commas $ % typed in the jtextfield on my taxcalculator code. But at the same time I need to fix it because when I try to run it again it does not because the validation adds $ to the field. This a simple form of validation such that if the user enters “$1, 499. 97” it will be converted to “1499.97”.
import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;
public class TaxCalculator7F extends JApplet {
JLabel subTotalJLabel, taxRateJLabel, totalTaxJLabel, totalSaleJLabel;
JTextField subTotalJTextField, taxRateJTextField, totalTaxJTextField, totalSaleJTextField;
JButton calculateTaxJButton;
public void init() {
setLayout(null); // allows explicit positioning of GUI components
Container myContent = getContentPane();
subTotalJLabel = new JLabel();
subTotalJLabel.setText("Sub Total: ");
subTotalJLabel.setBounds(10, 0, 100, 25);
myContent.add(subTotalJLabel);
subTotalJTextField = new JTextField();
subTotalJTextField.setText("0.00");
subTotalJTextField.setHorizontalAlignment(JTextField.RIGHT);
subTotalJTextField.setBounds(90, 0, 80, 25);
myContent.add(subTotalJTextField);
taxRateJLabel = new JLabel();
taxRateJLabel.setText("Tax Rate (%): ");
taxRateJLabel.setBounds(10, 40, 100, 25);
myContent.add(taxRateJLabel);
taxRateJTextField = new JTextField();
taxRateJTextField.setText("7");
taxRateJTextField.setHorizontalAlignment(JTextField.RIGHT);
taxRateJTextField.setBounds(90, 40, 80, 25);
myContent.add(taxRateJTextField);
totalTaxJLabel = new JLabel();
totalTaxJLabel.setText("Tax Due: ");
totalTaxJLabel.setBounds(10, 80, 100, 25);
myContent.add(totalTaxJLabel);
totalTaxJTextField = new JTextField();
totalTaxJTextField.setEditable(false);
totalTaxJTextField.setHorizontalAlignment(JTextField.RIGHT);
totalTaxJTextField.setBounds(90, 80, 80, 25);
myContent.add(totalTaxJTextField);
totalSaleJLabel = new JLabel();
totalSaleJLabel.setText("Total Sale: ");
totalSaleJLabel.setBounds(10, 120, 100, 25);
myContent.add(totalSaleJLabel);
totalSaleJTextField = new JTextField();
totalSaleJTextField.setEditable(false);
totalSaleJTextField.setHorizontalAlignment(JTextField.RIGHT);
totalSaleJTextField.setBounds(90, 120, 80, 25);
myContent.add(totalSaleJTextField);
calculateTaxJButton = new JButton();
calculateTaxJButton.setText("Calculate Tax");
calculateTaxJButton.setBounds(20, 160, 140, 30);
myContent.add(calculateTaxJButton);
calculateTaxJButton.addActionListener(
event -> {
// define variables
double subTotal, taxRate, taxDue, totalSale;
// get sales sub total and tax rate
subTotal = Double.parseDouble(subTotalJTextField.getText());
//subTotalJTextField.getText();
//Code to clear from field $ % ,
//subTotalJTextField.setText(String.valueOf(subTotal).replaceAll("(?<=\\d),(?=\\d)|\\$", ""));
taxRate = Double.parseDouble(taxRateJTextField.getText());
taxDue = subTotal * taxRate / 100;
totalSale = subTotal + taxDue;
DecimalFormat dollars = new DecimalFormat("$0.00");
DecimalFormat percent = new DecimalFormat("0.0%");
// test strings
subTotalJTextField.setText(dollars.format(subTotal));
taxRateJTextField.setText(percent.format(taxRate / 100.00));
totalTaxJTextField.setText(dollars.format(taxDue));
totalSaleJTextField.setText(dollars.format(totalSale));
}
);
}
}

well you could replace the $ sign
subTotal = Double.parseDouble(subTotalJTextField.getText().replace ("$", ""));
and the tax rate would be
taxRate = Double.parseDouble(taxRateJTextField.getText().replace ("%", ""));
or as #nandha points out
String money = "$1,234,000.67";
try {
NumberFormat format = NumberFormat.getCurrencyInstance();
Number number = format.parse(money);
System.out.println(number.doubleValue());
} catch (ParseException e) {
e.printStackTrace();
}

String subValue = subTotalJTextField.getText();
try {
NumberFormat format = NumberFormat.getCurrencyInstance();
Number number = format.parse(subValue);
subTotal = number.doubleValue();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
subTotal = 0;
}
Try this.
Refer this for more info

I think below code suits well to your problem
Number amount = null, rate = null;
try {
amount = NumberFormat.getCurrencyInstance().parse(subTotalJTextField.getText());
rate = NumberFormat.getNumberInstance().parse(taxRateJTextField.getText());
} catch (Exception e) {
e.printStackTrace();
amount = 0.0;
rate = 0.0;
}
subTotal = Double.parseDouble(String.valueOf(amount));
taxRate = Double.parseDouble(String.valueOf(rate));

Related

Outputting database data to a JTable

I've been trying to follow the information here and and the code here and I'm having some difficulty.
The database query works and I've outputted it successfully to console. Following the above guides I've since added some code that puts the ResultSet data into the required Vectors. This is my code:
public class Reports extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField dateFromYYYY;
private JTextField dateFromMM;
private JTextField dateFromDD;
private JTextField dateToYYYY;
private JTextField dateToMM;
private JTextField dateToDD;
private JTextField ownerNameInput;
private JTextField petNameInput;
private JTextField doctorNameInput;
private JCheckBox isPaid = new JCheckBox("Is Paid");
public static JTable table;
public static boolean printTable = true;
private String printHeader;
// Static Variables
private final static String BOOKINGS_TABLES = "FROM Doctor, Pet, Treatment, Visit ";
/**
* Create the frame.
*/
private void SearchFrame() {
setTitle("Generate a Report");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 981, 551);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblWhatWouldYou = new JLabel("What would you like a report for?");
lblWhatWouldYou.setBounds(36, 10, 200, 50);
contentPane.add(lblWhatWouldYou);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(260, 60, 690, 370);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
private void DateFields(){
// From Date
//Year
JLabel lblFromDate = new JLabel("From dd:");
lblFromDate.setBounds(20, 180, 165, 25);
contentPane.add(lblFromDate);
JLabel lblFromYear = new JLabel("yyyy:");
lblFromYear.setBounds(180, 180, 165, 25);
contentPane.add(lblFromYear);
dateFromYYYY = new JTextField();
dateFromYYYY.setBounds(210, 180, 40, 25);
contentPane.add(dateFromYYYY);
//Month
JLabel lblFromMonth = new JLabel("mm:");
lblFromMonth.setBounds(128, 180, 165, 25);
contentPane.add(lblFromMonth);
dateFromMM = new JTextField();
dateFromMM.setBounds(155, 180, 20, 25);
contentPane.add(dateFromMM);
dateFromDD = new JTextField();
dateFromDD.setBounds(100, 180, 20, 25);
contentPane.add(dateFromDD);
// To Date
//Year
JLabel lblToDate = new JLabel("To dd:");
lblToDate.setBounds(20, 210, 165, 25);
contentPane.add(lblToDate);
JLabel lblToYear = new JLabel("yyyy:");
lblToYear.setBounds(180, 210, 165, 25);
contentPane.add(lblToYear);
dateToYYYY = new JTextField();
dateToYYYY.setBounds(210, 210, 40, 25);
contentPane.add(dateToYYYY);
//Month
JLabel lblToMonth = new JLabel("mm:");
lblToMonth.setBounds(128, 210, 165, 25);
contentPane.add(lblToMonth);
dateToMM = new JTextField();
dateToMM.setBounds(155, 210, 20, 25);
contentPane.add(dateToMM);
dateToDD = new JTextField();
dateToDD.setBounds(100, 210, 20, 25);
contentPane.add(dateToDD);
}
private void PetName(){
JLabel lblPetName = new JLabel("Pet Name:");
lblPetName.setBounds(20, 90, 165, 25);
contentPane.add(lblPetName);
petNameInput = new JTextField();
petNameInput.setBounds(100, 90, 150, 25);
contentPane.add(petNameInput);
}
private void OwnerName(){
JLabel lblOwnerName = new JLabel("Owner Name:");
lblOwnerName.setBounds(20, 120, 165, 25);
contentPane.add(lblOwnerName);
ownerNameInput = new JTextField();
ownerNameInput.setBounds(100, 120, 150, 25);
contentPane.add(ownerNameInput);
}
private void DoctorName(){
JLabel lblDoctorName = new JLabel("Doctor Name:");
lblDoctorName.setBounds(20, 150, 165, 25);
contentPane.add(lblDoctorName);
doctorNameInput = new JTextField();
doctorNameInput.setBounds(100, 150, 150, 25);
contentPane.add(doctorNameInput);
}
private void IsPaidCheckBox(){
isPaid.setBounds(155, 250, 97, 25);
contentPane.add(isPaid);
}
public void Bookings() {
// Local variables
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
// Instantiate the frame
SearchFrame();
// Set search fields
PetName();
OwnerName();
DoctorName();
IsPaidCheckBox();
DateFields();
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String queryString00 = "";
String queryString01 = "SELECT pet.petname AS [Pet Name], pet.ownerName AS [Owner Name], doctor.doctorName AS [Doctor Name], visit.visitDate AS [Visit Date], treatment.treatmentName AS [Treatment Name], visit.ispaid AS [Is Paid] ";
String queryString03 = "WHERE Visit.petID = Pet.petID ";
String queryString02 = " GROUP BY visitID;";
// build the query
if(!(petNameInput.getText().equals("")))
queryString00 = queryString01 + BOOKINGS_TABLES + queryString03 + "AND petname LIKE " + "'%" + petNameInput.getText() + "%'";
else queryString00 = queryString01 + BOOKINGS_TABLES + queryString03;
if(!(ownerNameInput.getText().equals("")))
queryString00 = queryString00 + "AND ownername LIKE " + "'%" + ownerNameInput.getText() + "%'";
if(!(doctorNameInput.getText().equals("")))
queryString00 = queryString00 + "AND doctorname LIKE " + "'%" + doctorNameInput.getText() + "%'";
if(!(dateFromYYYY.getText().equals(""))){
String fromString = dateFromYYYY.getText() + "-" + dateFromMM.getText() + "-" + dateFromDD.getText();
queryString00 = queryString00 + " AND visitdate >= '" + fromString + "'";
}
if(!(dateToYYYY.getText().equals(""))){
String toString = dateToYYYY.getText() + "-" + dateToMM.getText() + "-" + dateToDD.getText();
queryString00 = queryString00 + " AND visitdate <= '" + toString + "'";
}
if(isPaid.isSelected())
queryString00 = queryString00 + " AND ispaid = 'Y'";
queryString00 = queryString00 + queryString02;
// System.out.println(queryString00);
DatabaseConnection db = new DatabaseConnection();
db.openConn();
// Get query
ResultSet rs = db.getSearch(queryString00);
ResultSetMetaData md = null;
// Set up vectors for table output
// Output query to screen (Much of the following code is adapted from http://www.camick.com/java/source/TableFromDatabase.java)
try{
md = rs.getMetaData();
int columnCount = md.getColumnCount();
// Get column names
for(int i = 1; i <= columnCount; i++)
columnNames.addElement(md.getColumnName(i));
while(rs.next()){
// System.out.printf("%-15s%-15s%-15s%-15s%-15s%-15s\n", rs.getString("Pet Name"), rs.getString("Owner Name"), rs.getString("Doctor Name"), rs.getString("Visit Date"), rs.getString("Treatment Name"), rs.getString("Is Paid"));
Vector<Object> row = new Vector<Object>(columnCount);
for(int i = 1; i <= columnCount; i++)
row.addElement(rs.getObject(i));
data.addElement(row);
}
}
catch (SQLException e) {
e.printStackTrace();
}
db.closeConn();
}
// Create table with database data
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
/**
*
*/
private static final long serialVersionUID = 1L;
#SuppressWarnings("unchecked")
#Override
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
// Out put to the table (theoretically)
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
// JScrollPane scrollPane = new JScrollPane( table );
// getContentPane().add( scrollPane );
});
btnSearch.setBounds(36, 460, 165, 25);
contentPane.add(btnSearch);
JLabel resultLabel = new JLabel("Reports will be printed below");
resultLabel.setBounds(515, 10, 312, 50);
contentPane.add(resultLabel);
JButton printReport = new JButton("Print Report");
printReport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String resultLabelPrint = resultLabel.getText();
MessageFormat footer = new MessageFormat(resultLabelPrint);
MessageFormat header = new MessageFormat(printHeader);
boolean complete =table.print(JTable.PrintMode.FIT_WIDTH, header , footer );
if (complete) {
/* show a success message */
} else {
/*show a message indicating that printing was cancelled */
}
} catch (PrinterException pe) {
/* Printing failed, report to the user */
}
}
});
printReport.setBounds(473, 460, 227, 25);
contentPane.add(printReport);
}
}
The final part of the code, which I believe out puts to the table, gives me some weird errors.
// Out put to the table (theoretically)
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
// JScrollPane scrollPane = new JScrollPane( table );
// getContentPane().add( scrollPane );
The first line gives me a syntax error on the semi-colon (;), specifically, Syntax error on token ";", invalid AssignmentOperator. I get the same when I try the 'model' variable.
When I uncomment the last two lines I get 'Syntax error on token ".", { expected' and the Eclipse demands another closing { despite there not being a corresponding opening }. If I add it then I get more errors.
I suspect this has something to do with the class structure of the code that I'm trying to follow but I'm having no luck in following those either.
All I want to do is to take the information that I have and output it in the table which is already there. How do I do this?
You're not showing all the error messages nor the complete error messages (please fix this). The most important one is the, Cannot refer to the non-final local variable data defined in an enclosing scope message. So make the variables final -- one problem solved.
public void Bookings() {
// Local variables
final Vector<Object> columnNames = new Vector<Object>(); //!! made final
final Vector<Object> data = new Vector<Object>();
The other problem is that this code:
JTable table = new JTable(columnNames, data);
this.scrollPane.setViewportView(table);
Is being called outside of any and all methods. You need to match up your curly braces carefully.
Question that confuses me about your code though -- why create a TableModel and not use it as a model for your JTable?
scrollPane is not a global instance.
Move JScrollPane scrollPane out of your method SearchFrame() and place it into your list of instance variables for the class.
That is only your immediate and first issue, your other issue is that your are attempting to access instance variables defined in Reports within the scope of 2x nested anonymous classes.
You should parametarize your GUI methods to accept the components for injection into the panels.
public class Reports extends JFrame {
JScrollPane scrollPane;
...
private void SearchFrame() {
scrollPane = new JScrollPane ();
}
...
public void Bookings() {
scrollPane...
...
}
...
}

Getting a java;23 error; saying '{' is expected but brackets look fine to me [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
please help getting "java:23 error: '{' expected" to me the brackets look right, appreciate the help!
is there something else that I am missing? I've only just started getting into writing code and so far have loved it. I've done c# and visual basics as well as now taking Java.
//Pizza applet to assist customers when ordering pizza
//I had to make a pizza during this assignment :)
//Import packages
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PizzaShop extends JApplet
{
//Declare variables
private int intBold;
private JCheckbox tomatoCB, grennPepperCB, blackOliveCB;
private JCheckBox MushroomCB, extraCheeseCB, pepperoniCB, sausageCB;
private JRadioButton smallRB, mediumRB, largeRB;
private JRadioButton thinRB, halfRB, panPizzaRB;
private ButtonGroup sizeBG, typeBG;
private JTextArea textArea;
private Jbutton processB;
private JLabel orderL;
private EventHandler eHandler;
}
public class PizzaShop()
{
public void init()
{
//Set up layout
Container c = getContentPane();
c.setLayout(null);
eHandler = new EventHandler();
//Establish checkboxes
tomatoCB = new JCheckBox("Tomato");
greenPepperCB = new JCheckBox("Green Pepper");
blackOliveCB = new JCheckBox("Black Olive");
mushroomCB = new JCheckBox("Mushroom");
extraCheeseCB = new JCheckBox("Extra Cheese");
pepperoniCB = new JCheckBox("Pepperoni");
sausageCB = new JCheckBox("Sausage");
//Set size and location
tomatoCB.setSize(100, 25);
greenPepperCB.setSize(100, 25);
blackOliveCB.setSize(100, 25);
mushroomCB.setSize(100, 25);
extraCheeseCB.setSize(100, 25);
pepperoniCB.setSize(100, 25);
sausageCB.setSize(100, 25);
tomatoCB.setLocation(50, 85);
greenPepperCB.setLocation(50, 110);
blackOliveCB.setLocation(50, 135);
mushroomCB.setLocation(50, 160);
extraCheeseCB.setLocation(50, 185);
pepperoniCB.setLocation(50, 210);
sausageCB.setLocation(50, 235);
//Add CheckBox to layout
c.add(tomatoCB);
c.add(greenPepperCB);
c.add(blackOliveCB);
c.add(mushroomCB);
c.add(extraCheeseCB);
c.add(pepperoniCB);
c.add(sausageCB);
//Set pizza size radio buttons
smallRB = newJRadioButton("Small $6.50");
mediumRB = newJRadioButton("Medium $8.50");
largeRB = newJRadioButton("Large: $10.00");
//Set size and location of pizza buttons
smallRB.setSize(100, 25);
mediumRB.setSize(100, 25);
largeRB.setSize(100, 25);
smallRB.setLocation(225, 90);
mediumRB.setLocation(225, 130);
largeRB.setLocation(225, 170);
//Set group for pizza size
sizeBG = new ButtonGroup();
sizeBG.add(smallRB);
sizeBG.add(mediumRB);
sizeBG.add(largeRB);
c.add(smallRB);
c.add(mediumRB);
c.add(largeRB);
//Set pizza type
thinRB = new JRadioButton("Thin Crust");
halfRB = newJRadioButton("Medium Crust");
panPizzaRB = new JRadioButton("Pan");
//Set pizza type size and location
thinRB.setSize(100, 25);
halfRB.setSize(100, 25);
panRB.setSize(100, 25);
thinRB.setLocation(370, 90);
half.setLocation(370, 130);
PanRB.setLocation(370, 170);
//Set type of pizza to button group
typeBG = new ButtonGroup();
typeBG.add(thinRB);
typeBG.add(halfRB);
typeBG.add(panRB);
c.add(thinRB);
c.add(halfRB);
c.add(panRB);
//Add process button set size and location and activate event
processB = new JButton("Process Order");
processB.setSize(200, 30);
processB.setLocation(210, 220);
c.add(processB);
processB.addActionListener(eHandler);
//Add label for output and set size and location
orderL = new JLabel("Your Order:");
orderL.setSize (100, 30);
orderL.setLocation(40, 270);
c.add(orderL);
textArea = new JTextArea();
textArea.setVisible(true);
textArea.setSize(450, 110);
textArea.setLocation(40, 300);
c.add(textArea);
}
public void paint(Graphics g)
{
super.paint(g);
//Set text for welcome greeting
g.setColor(Color.red);
g.setFont(new Font("Times New Roman", intBold, 24));
g.drawString("Welcome to Home Style Pizza Shop", 30, 30);
//Set text for each topping
g.setFont(new Font("Times New Roman", intBold, 24));
g.drawString("Each Topping: $1.50", 40, 80);
g.drawRect(30, 60, 150, 210);
//Set text for pizza size and type
g.drawString("Pizza Size", 220, 80);
g.drawRect(210, 60, 130, 150);
g.drawString("Pizza Type", 370, 80);
g.drawRect(360, 60, 130, 150);
}
private class EventHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//Declare variables
double amountDue = 0.0;
String str = " ";
//See whats checked in pizza type
if (e.getSource() == processB);
{
str = str + "Pizza Type:";
if (thinRB.isSelected())
str = str + "Thin Crust \n";
else if (halfRB.isSelected())
str = str + " Medium Crust \n";
else if (panRB.isSelected())
str = str + "Pan Crust \n";
}
str = str + "Pizza Size: ";
//See what's checked in pizza size
if(smallRB.isSelected())
{
str = str + "Small \n";
amountDue = amountDue + 6.50;
}
else if (mediumRB.isSelected())
{
str = str + "Medium \n";
amountDue = amountDue + 8.50;
}
else if (largeRB.isSelected())
{
str = str + "Large \n";
amountDue = smountDue = 10.00;
}
str = str + "Toppings: ";
//Check toppings add 1.50 each per checked box
if (tomatoCB.isSelected())
{
str = str + "Tomato, ";
amountDue = amountDue + 1.50;
}
if (greenPepperCB.isSelected())
{
str = str + "Green Pepper, ";
amountDue = amountDue + 1.50;
}
if (blackOliveCB.isSelected())
{
str = str + "Black Olive, ";
amountDue = amountDue + 1.50;
}
if (mushroomCB.isSelected())
{
str = str + "Mushroom, ";
amountDue = amountDue + 1.50;
}
if (extraCheeseCB.isSelected())
{
str = str + "Extra Cheese, ";
amountDue = amountDue + 1.50;
}
if (pepperoniCB.isSelected())
{
str = str + "Pepperoni, ";
amountDue = amountDue + 1.50;
}
if (sausageCB.isSelected())
{
str = str + "Sausage, ";
amountDue = amountDue + 1.50;
}
//Display order
str = str + "\nAmount Due: $" = amountDue;
textArea.setText(str);
}
}
}
The } after private EventHandler eHandler; will close the class definition, which is not what you are wanting.
Also public class PizzaShop() { would be wrong and not needed. Maybe you are thinking of a constructor?
I suggest that you use a IDE like eclipse which allows you to click on menu items to create classes etc.
Your closing brace on line 22 is finishing the class definition and the code after that seems to be trying to re-start it. Get rid of it. You should have:
private JLabel orderL;
private EventHandler eHandler;
public void init() { ...
There is an extra closing brace before
public class PizzaShop()
And I presume the above line is meant to be a constructor, not another class declaration:
public PizzaShop() {
}
You can't have the same class defined twice in a file, in fact each class should probably be in another file (or it needs to be an inner class of some kind) -
public class PizzaShop extends JApplet
{
//Declare variables
private int intBold;
private JCheckbox tomatoCB, grennPepperCB, blackOliveCB;
private JCheckBox MushroomCB, extraCheeseCB, pepperoniCB, sausageCB;
private JRadioButton smallRB, mediumRB, largeRB;
private JRadioButton thinRB, halfRB, panPizzaRB;
private ButtonGroup sizeBG, typeBG;
private JTextArea textArea;
private Jbutton processB;
private JLabel orderL;
private EventHandler eHandler;
} // <-- Here
public class PizzaShop() // <-- we just did this class.

Radio Button Groups and extra options

So I am having a problem with my Java program. I currently want it to have 3 main course options Hamburger, Pizza, and Salad with add on options. Now currently the program starts with Hamburger selected and the add-ons available they calculate price as well. When the main item is selected the add-on options should change with the new item however they don't. I have been staring at this for awhile now so it could be I am missing something really simple like clearing the area and then having the new add-on options show. In any case any help would be appreciated, here is the current code.
import java.awt.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
public class LunchOrder extends JFrame {
private JRadioButton hamburgerJButton, pizzaJButton, saladJButton;
private JCheckBox lettuceButton, mayonnaiseButton, mustardButton, pepperoniButton,
sausageButton, mushroomsButton, croutonsButton, baconBitsButton, breadSticksButton;
private JLabel subTotal, tax, totalDue;
private JTextField subTotalText, taxText, totalDueText;
private JButton placeOrder, clearOrder, exitButton;
// no-argument constructor
public LunchOrder()
{
createUserInterface();
}
// create and position GUI components; register event handlers
private void createUserInterface()
{
// get content pane for attaching GUI components
Container contentPane = getContentPane();
// enable explicit positioning of GUI components
contentPane.setLayout( null);
hamburgerJButton = new JRadioButton("Hamburger - $6.95" );
hamburgerJButton.setSelected(true);
pizzaJButton = new JRadioButton("Pizza - $5.95");
pizzaJButton.setSelected(false);
saladJButton = new JRadioButton("Salad - $4.95");
saladJButton.setSelected(false);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(hamburgerJButton);
bgroup.add(pizzaJButton);
bgroup.add(saladJButton);
JPanel mainCourse = new JPanel();
mainCourse.setLayout( new GridLayout( 3, 1 ));
mainCourse.setBounds( 10, 10, 150,135 );
mainCourse.add(hamburgerJButton);
mainCourse.add(pizzaJButton);
mainCourse.add(saladJButton);
mainCourse.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Main course" ) );
//contentPane.add( mainCourseJPanel, BorderLayout.NORTH );
contentPane.add( mainCourse );
//Add action listener to created button
//JCheckBox
lettuceButton = new JCheckBox("Lettuce, tomato, and onions");
lettuceButton.setSelected(true);
mayonnaiseButton= new JCheckBox("Mayonnaise");
mayonnaiseButton.setSelected(false);
mustardButton = new JCheckBox("Mustard");
mustardButton.setSelected(true);
pepperoniButton = new JCheckBox("Pepperoni");
sausageButton= new JCheckBox("Sausage");
mushroomsButton = new JCheckBox("Mushrooms");
croutonsButton = new JCheckBox("Croutons");
baconBitsButton= new JCheckBox("Bacon bits");
breadSticksButton = new JCheckBox("Bread sticks");
//JPanel addons
JPanel addOns = new JPanel();
GridLayout addOnGlay = new GridLayout(3,3);
addOns.setLayout(addOnGlay);
addOns.setBounds( 250, 10, 250, 135 );
addOns.add(lettuceButton);
addOns.add(pepperoniButton);
addOns.add(croutonsButton);
addOns.add(mayonnaiseButton);
addOns.add(sausageButton);
addOns.add(baconBitsButton);
addOns.add(mustardButton);
addOns.add(mushroomsButton);
addOns.add(breadSticksButton);
pepperoniButton.setVisible(false);
sausageButton.setVisible(false);
mushroomsButton.setVisible(false);
croutonsButton.setVisible(false);
baconBitsButton.setVisible(false);
breadSticksButton.setVisible(false);
addOns.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Add ons($.25/each)" ) );
contentPane.add( addOns );
// subtotal JLabel
subTotal = new JLabel();
subTotal.setBounds(10, 110, 100, 200);
contentPane.add(subTotal);
subTotal.setText( "Subtotal: " );
subTotal.setHorizontalAlignment(JLabel.RIGHT);
// subtotal JTextField
subTotalText = new JTextField();
subTotalText.setBounds(115, 200, 80, 22);
subTotalText.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(subTotalText);
// Tax JLabel
tax = new JLabel();
tax.setBounds(10, 135, 100, 200);
contentPane.add(tax);
tax.setText("Tax(7.85%) ");
tax.setHorizontalAlignment(JLabel.RIGHT);
// Tax JTextField
taxText = new JTextField();
taxText.setBounds(115, 225, 80, 22);
contentPane.add(taxText);
// total due JLabel
totalDue = new JLabel();
totalDue.setBounds(10, 160, 100, 200);
contentPane.add(totalDue);
totalDue.setText("Total due: " );
totalDue.setHorizontalAlignment(JLabel.RIGHT);
// total due JTextField
totalDueText = new JTextField();
totalDueText.setBounds(115, 250, 80, 22);
contentPane.add(totalDueText);
// order total JPanel
JPanel orderTotal = new JPanel();
GridLayout orderGLay = new GridLayout(3,1);
orderTotal.setLayout(orderGLay);
orderTotal.setBounds(10, 170, 200, 125 );
orderTotal.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Order total" ) );
contentPane.add( orderTotal );
// place order JButton
placeOrder = new JButton();
placeOrder.setBounds( 252, 175, 100, 24 );
placeOrder.setText( "Place order" );
contentPane.add( placeOrder );
placeOrder.addActionListener(
new ActionListener() // anonymous inner class
{
// event handler called when calculateJButton is pressed
public void actionPerformed(ActionEvent event) {
placeOrderActionPerformed(event);
}
} // end anonymous inner class
); // end call to addActionListener
// set up clearOrderJButton
clearOrder = new JButton();
clearOrder.setBounds(252,210, 100, 24 );
clearOrder.setText( "Clear order" );
contentPane.add( clearOrder );
clearOrder.addActionListener(
new ActionListener() // anonymous inner class
{
// event handler called when calculateJButton is pressed
public void actionPerformed(ActionEvent event) {
clearOrderActionPerformed(event);
}
} // end anonymous inner class
); // end call to addActionListener
// set up exitJButton
exitButton = new JButton();
exitButton.setBounds( 425, 260, 70, 24 );
exitButton.setText( "Exit" );
contentPane.add( exitButton );
// set properties of application's window
setTitle( "Lunch order" ); // set window title
setResizable(true); // prevent user from resizing window
setSize( 525, 350 ); // set window size
setVisible( true ); // display window
setLocationRelativeTo(null);
}
// calculate subtotal plus tax
private void placeOrderActionPerformed(ActionEvent event) {
DecimalFormat dollars = new DecimalFormat("$0.00");
// declare double variables
double hamburgerPrice = 6.95;
double pizzaPrice = 5.95;
double saladPrice = 4.95;
double addons = 0;
double subTotPrice;
double taxPercent;
double totalDuePrice;
if ( hamburgerJButton.isSelected())
{
if( lettuceButton.isSelected()){
addons += 0.25;
}
if( mayonnaiseButton.isSelected()){
addons += 0.25;
}
if( mustardButton.isSelected()){
addons += 0.25;
}
else{
addons -= 0.25;
}
subTotPrice = hamburgerPrice + addons;
taxPercent = subTotPrice * 0.0785;
totalDuePrice = subTotPrice + taxPercent;
//display subtotal, tax and total due
subTotalText.setText( dollars.format( subTotPrice ));
taxText.setText( dollars.format( taxPercent));
totalDueText.setText( dollars.format( totalDuePrice ));
}
if ( pizzaJButton.isSelected())
{
//lettuceButton.setVisible(false);
//mayonnaiseButton.setVisible(false);
//mustardButton.setVisible(false);
croutonsButton.setVisible(false);
baconBitsButton.setVisible(false);
breadSticksButton.setVisible(false);
pepperoniButton.setVisible(true);
sausageButton.setVisible(true);
mushroomsButton.setVisible(true);
//calculation for pizza selection
if( pepperoniButton.isSelected())
addons += 0.25;
if( sausageButton.isSelected())
addons += 0.25;
if( mushroomsButton.isSelected())
addons += 0.25;
else
addons -= 0.25;
subTotPrice = (pizzaPrice + addons);
taxPercent = subTotPrice * 0.0785;
totalDuePrice = subTotPrice + taxPercent;
//display subtotal, tax and total due
subTotalText.setText( dollars.format( subTotPrice ));
taxText.setText( dollars.format( taxPercent));
totalDueText.setText( dollars.format( totalDuePrice ));
}
if ( saladJButton.isSelected())
{
croutonsButton.setVisible(true);
baconBitsButton.setVisible(true);
breadSticksButton.setVisible(true);
if( croutonsButton.isSelected())
addons += 0.25;
if( baconBitsButton.isSelected())
addons += 0.25;
if( breadSticksButton.isSelected())
addons += 0.25;
else
addons -= 0.25;
//calculation for salad selection
subTotPrice = (saladPrice + addons);
taxPercent = subTotPrice * 0.0785;
totalDuePrice = subTotPrice + taxPercent;
//display subtotal, tax and total due
subTotalText.setText( dollars.format( subTotPrice ));
taxText.setText( dollars.format( taxPercent));
totalDueText.setText( dollars.format( totalDuePrice ));
}
} // end method calculateJButtonActionPerformed
private void clearOrderActionPerformed(ActionEvent event) {
//reset hamburger and addons to default state
hamburgerJButton.setSelected(true);
lettuceButton.setSelected(true);
mayonnaiseButton.setSelected(false);
mustardButton.setSelected(true);
subTotalText.setText("");
taxText.setText("");
totalDueText.setText("");
} // end method calculateJButtonActionPerformed
public static void main( String args[] )
{
LunchOrder application = new LunchOrder();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
You've not added any listeners that could notify of any kind of state change, Java can't magically know what you want it to...I wish...
You could use a ItemListener on each of the buttons, and based on what's selected, make a change to your UI, for example...
Create you're self a ItemListener...
ItemListener il = new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("Hamburger = " + hamburgerJButton.isSelected());
System.out.println("Pizza = " + pizzaJButton.isSelected());
System.out.println("Salad = " + saladJButton.isSelected());
}
}
};
And after you've initalised your buttons, register it with each of them...
hamburgerJButton.addItemListener(il);
pizzaJButton.addItemListener(il);
saladJButton.addItemListener(il);
Take a look at How to use buttons for more details

Java Mortgage Calculator Reading a Sequential File [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I populate jcombobox from a textfile?
OK, I have an issue here that I cannot quiet figure out. I have a file that has variables on each line of: 5.35, 5.5, 5.75 in a file called apr.txt. I am reading the file and need to populate the file into a JComboBox. So far I have the file being read fine but cannot figure how to populate it into the JComboBox. This must be something easy. Can someone help point me in the proper direction?
Thank you for your help in advance.
import java.awt.*;
import java.text.NumberFormat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.JComboBox;
public class MortgageCalculatorGUI9 extends JFrame implements ActionListener
{
// Declarations
//double [] Interest = {5.35, 5.5, 5.75};
int [] Length = {7, 15, 30};
double [] file_data = new double[3];
JLabel mortgagelabel = new JLabel( "Principal Amount:$ " );
JLabel paymentLabel = new JLabel( "Monthly Payment: " );
JLabel intRateLabel = new JLabel( "Interest Rate %: " );
JLabel termLabel = new JLabel( "Length of Loan of Loan in Years: " );
JTextField mortgagePrincipal = new JTextField(7);
JTextField Payment = new JTextField(7);
//JTextField intRateText = new JTextField(3);
JComboBox intRateBox = new JComboBox();
JTextField termText = new JTextField(3);
JButton b7_535 = new JButton( "7 years at 5.35%" );
JButton b15_55 = new JButton( "15 years at 5.50%" );
JButton b30_575 = new JButton( "30 years at 5.75%");
JButton exitButton = new JButton( "Exit" );
JButton clearButton = new JButton( "Clear All" );
JButton calculateButton = new JButton( "Calculate Loan" );
JTextArea LoanPayments = new JTextArea(20,50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public MortgageCalculatorGUI9()
{
//GUI setup
super("Mortgage Calculator 1.0.5");
setSize(800, 400);
setLocation(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(3,1)); Container grid = getContentPane();
grid.setLayout(new GridLayout(4,0,4,4)); pane.add(grid);
pane.add(scroll);
grid.add(mortgagelabel);
grid.add(mortgagePrincipal);
grid.add(intRateLabel);
//grid.add(intRateText);
grid.add (intRateBox);
grid.add(termLabel);
grid.add(termText);
grid.add(paymentLabel);
grid.add(Payment);
grid.add(b7_535);
grid.add(b15_55);
grid.add(b30_575);
grid.add(calculateButton);
grid.add(clearButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
//add GUI functionality
calculateButton.addActionListener (this);
exitButton.addActionListener(this);
clearButton.addActionListener(this);
b7_535.addActionListener(this);
b15_55.addActionListener(this);
b30_575.addActionListener(this);
mortgagePrincipal.addActionListener(this);
//intRateText.addActionListener(this);
intRateBox.addActionListener (this);
termText.addActionListener(this);
Payment.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object command = e.getSource();
if (command == exitButton)
{
System.exit(0);
}
else if (command == b7_535)
{
calcLoan(Length[0], file_data[0]);
}
else if (command == b15_55)
{
calcLoan(Length[1], file_data[1]);
}
else if (command == b30_575)
{
calcLoan(Length[2], file_data[2]);
}
else if (command == calculateButton )
{
double terms = 0;
double rates = 0;
try
{
terms = Double.parseDouble(termText.getText());
//rates = Double.parseDouble(intRateText.getText());
read_File ();
}
catch (Exception ex)
{
LoanPayments.setText("Invalid term or rate Amount");
return;
}
calcLoan(terms, rates);
}
else if (command == clearButton)
{
mortgagePrincipal.setText("");
Payment.setText("");
//intRateText.setText("");
termText.setText("");
LoanPayments.setText("");
}
}
//Input File
public void read_File()
{
File inFile = new File("apr.txt");
try
{
BufferedReader istream = new BufferedReader(new FileReader(inFile));
for(int x=0;x<6;x++)
{
file_data[x]=Double.parseDouble (istream.readLine());
}
}
catch (Exception ex)
{
LoanPayments.setText ("Could Not Read From File.");
return;
}
}
//this is what needs to be done
private void calcLoan(double terms, double rates)
{
termText.setText(String.valueOf(terms) );
//intRateText.setText(String.valueOf(rates));
double amount = 0;
try
{
amount = Double.parseDouble(mortgagePrincipal.getText());
}
catch (Exception ex)
{
LoanPayments.setText("Invalid mortgage Amount");
return;
}
double interestRate = rates;
// Calculations
double intRate = (interestRate / 100) / 12;
int Months = (int)terms * 12;
double rate = (intRate / 12);
double payment = amount * intRate / (1 - (Math.pow(1/(1 + intRate), Months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
double[] balanceArray = new double[Months];
double[] interestArray = new double[Months];
double[] monthArray = new double[Months];
NumberFormat Money = NumberFormat.getCurrencyInstance();
Payment.setText(Money.format(payment));
LoanPayments.setText("Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while(currentMonth < Months)
{
//create loop calculations
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t" + Money.format(MonthlyAmt) + "\t" + Money.format(MonthlyInterest) + "\t" + Money.format(remainingPrincipal) + "\n");
balanceArray[currentMonth] = MonthlyAmt;
interestArray[currentMonth] = MonthlyInterest;
monthArray[currentMonth] = currentMonth;
}
}
public static void main(String[] args)
{
MortgageCalculatorGUI9 frame= new MortgageCalculatorGUI9();
}
}
Have you looked at the JComboBox API for a suitable method? If you start there, you'll likely get the right answer faster than asking in StackOverflow (hint it starts with "add... and ends with ...Item") ;)

Java radio buttons

I'm having trouble with my radio buttons. I can click on all three at the same time. It should be when you click on one the other one turns off?
I'm using a grid layout. So when I try group.add it doesn't work.
Example:
I have the buttons declared like this
JRadioButton seven = new JRadioButton("7 years at 5.35%", false);
JRadioButton fifteen = new JRadioButton("15 years at 5.5%", false);
JRadioButton thirty = new JRadioButton("30 years at 5.75%", false);
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
This is my code:
/*Change Request #6
Write the program in Java (with a graphical user interface)
so that it will allow the user to select which way
they want to calculate a mortgage:
by input of the amount of the mortgage,
the term of the mortgage,
and the interest rate of the mortgage payment
or by input of the amount of a mortgage and
then select from a menu of mortgage loans:
- 7 year at 5.35%
- 15 year at 5.5 %
- 30 year at 5.75%
In either case, display the mortgage payment amount
and then, list the loan balance and interest paid
for each payment over the term of the loan.
Allow the user to loop back and enter a new amount
and make a new selection, or quit.
Insert comments in the program to document the program.
*/
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WK4 extends JFrame implements ActionListener
{
int loanTerms[] = { 7, 15, 30 };
double annualRates[] = { 5.35, 5.5, 5.75 };
// Labels
JLabel AmountLabel = new JLabel(" Loan Amount $ ");
JLabel PaymentLabel = new JLabel(" Monthly Payment ");
JLabel InterestLabel = new JLabel(" Interest Rate % ");
JLabel TermLabel = new JLabel(" Years of Loan ");
// Text Fields
JTextField mortgageAmount = new JTextField(6);
JTextField Payment = new JTextField(6);
JTextField InterestRate = new JTextField(3);
JTextField Term = new JTextField(3);
// Radio Buttons
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton seven = new JRadioButton("7 years at 5.35%");
JRadioButton fifteen = new JRadioButton("15 years at 5.5%");
JRadioButton thirty = new JRadioButton("30 years at 5.75%");
// Buttons
JButton exitButton = new JButton("Exit");
JButton resetButton = new JButton("Reset");
JButton calculateButton = new JButton("Calculate ");
// Text Area
JTextArea LoanPayments = new JTextArea(20, 50);
JTextArea GraphArea = new JTextArea(20, 50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public WK4(){
super("Mortgage Calculator");
//Window
setSize(700, 400);
setLocation(200, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(2, 2));
Container grid = getContentPane();
grid.setLayout(new GridLayout(4, 10, 0, 12)); //rows, cols, hgap, vgap
pane.add(grid);
pane.add(scroll);
grid.add(AmountLabel);
grid.add(mortgageAmount);
grid.add(InterestLabel);
grid.add(InterestRate);
grid.add(TermLabel);
grid.add(Term);
grid.add(PaymentLabel);
grid.add(Payment);
grid.add(Box.createHorizontalStrut(15));
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
grid.add(calculateButton);
grid.add(resetButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
// Action Listeners
mortgageAmount.addActionListener(this);
InterestRate.addActionListener(this);
Term.addActionListener(this);
Payment.addActionListener(this);
seven.addActionListener(this);
fifteen.addActionListener(this);
thirty.addActionListener(this);
calculateButton.addActionListener(this);
exitButton.addActionListener(this);
resetButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object command = e.getSource();
if (command == exitButton) {
System.exit(0);
}
else if (command == seven) {
calcLoan(loanTerms[0], annualRates[0]);
}
else if (command == fifteen) {
calcLoan(loanTerms[1], annualRates[1]);
}
else if (command == thirty) {
calcLoan(loanTerms[2], annualRates[2]);
}
else if (command == calculateButton) {
double years = 0;
double rates = 0;
try {
years = Double.parseDouble(Term.getText());
rates = Double.parseDouble(InterestRate.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
calcLoan(years, rates);
}
else if (command == resetButton) {
mortgageAmount.setText("");
Payment.setText("");
InterestRate.setText("");
Term.setText("");
LoanPayments.setText("");
}
}
private void calcLoan(double years, double rates) {
Term.setText(String.valueOf(years));
InterestRate.setText(String.valueOf(rates));
double amount = 0;
try {
amount = Double.parseDouble(mortgageAmount.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
double interestRate = rates;
double intRate = (interestRate / 100) / 12;
int months = (int) years * 12;
double rate = (intRate / 12);
double payment = amount * intRate
/ (1 - (Math.pow(1 / (1 + intRate), months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
NumberFormat CurrencyFormatter = NumberFormat.getCurrencyInstance();
Payment.setText(CurrencyFormatter.format(payment));
LoanPayments.setText(" Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while (currentMonth < months) {
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t"
+ CurrencyFormatter.format(MonthlyAmt) + "\t"
+ CurrencyFormatter.format(MonthlyInterest) + "\t"
+ CurrencyFormatter.format(remainingPrincipal) + "\n");
GraphArea.append("" + remainingPrincipal);
}
}
public static void main(String[] args) {
new WK4();
}
}
You're adding the radio buttons to the grid but you also need to add them to the button group that you defined.
Maybe this:
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
Should be this: ??? (Copy/paste bug?)
ButtonGroup group = new ButtonGroup();
group.add(seven);
group.add(fifteen);
group.add(thirty);
Or maybe you need to do both. The radio buttons have to belong to a container as well as a button group to be displayed and to behave properly.

Categories