I am not running into any errors but nothing happens when I run the program. Any help would be appreciated. I just need to be able to add a starting balance and then calculate a deposit or withdraw.
package account;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class GUI implements ActionListener{
JTextField txt, txt2, txt3;
JButton submit;
JLabel balance;
double Balance = 0.00;
GUI(){
JFrame main = new JFrame("Account GUI ");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt = new JTextField(10);
txt2 = new JTextField(10);
txt3 = new JTextField(10);
JPanel gui = new JPanel(new BorderLayout(8,8));
gui.setBorder(new EmptyBorder(8,8,8,8));
main.setContentPane(gui);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Starting Balance"));
controls.add(txt);
txt.addActionListener(this);
labels.add(new JLabel("Deposit Amount: "));
controls.add(txt2);
txt2.addActionListener(this);
labels.add(new JLabel("Withdraw Amount: "));
controls.add(txt3);
txt3.addActionListener(this);
submit = new JButton("Submit");
gui.add(submit, BorderLayout.SOUTH);
balance = new JLabel("New Balance " + Balance);
gui.add(balance,BorderLayout.NORTH);
submit.addActionListener(this);
main.pack();
main.setVisible(true);
}
public void actionPerformed(ActionEvent arg0) {
if (txt!=null){
double strtblnc = Double.parseDouble(txt.getText());
Balance = Balance + strtblnc;
}
else if (txt2!=null){
double dpst = Double.parseDouble(txt2.getText());
Balance = Balance + dpst;
}
else if(txt3!=null){
double wthdrw = Double.parseDouble(txt3.getText());
Balance = Balance - wthdrw;
}
}
public static void main(String[] args) {
GUI test = new GUI();
}
}
The reason why you are not receiving a new balance number is because you are never actually resetting the text to your JLabel. When you originally initialized:
balance = new JLabel("New Balance " + Balance);
You set Balance to 0.00. With that being said, you will need to add:
balance.setText("New Balance " + Balance);
to give you the updated Balance.
I also noticed that the code you posted did not work if you left a text field blank. Look at the updated code below and try this.
public void actionPerformed(ActionEvent arg0) {
double strtblnc;
double dpst;
double wthdrw;
String sTxt = txt.getText();
String sTxt2 = txt2.getText();
String sTxt3 = txt3.getText();
if(sTxt.isEmpty())
sTxt = "0";
if(sTxt2.isEmpty())
sTxt2 = "0";
if(sTxt3.isEmpty())
sTxt3 = "0";
dpst = Double.parseDouble(sTxt2);//parses deposit;
strtblnc = Double.parseDouble(sTxt); //parses starting balance;
wthdrw = Double.parseDouble(sTxt3); //parses withdraw;
Balance = Balance + strtblnc + dpst - wthdrw;
balance.setText("New Balance " + Balance);
}
Related
I don't understand how I can have two classes displayed once I have already used up one of the corners (NORTH, EAST, WEST, SOUTH), how can I add a fifth class by using border layout? as you can see in the build buttons area, I need to be able to have two classes in the are, I don't care where the tastybois class goes I just need to be able to have 5 things displayed.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class IkeaRun extends JFrame{
private IkeaMainDish Dish;
private Drinks drinks;
private SideDish Side;
private IkeaGreetings greeting;
private TastyBois tastybois;
private JPanel mainPanel;
private JButton calcButton;
private JButton exitButton;
private final double taxRate = 0.06;
public IkeaRun(){
setTitle("ORDER");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
greeting = new IkeaGreetings();
Dish = new IkeaMainDish();
drinks = new Drinks();
Side = new SideDish();
tastybois = new TastyBois();
buildButtons();
add(greeting, BorderLayout.NORTH);
add(Dish, BorderLayout.WEST);
add(drinks, BorderLayout.CENTER);
add(Side, BorderLayout.EAST);
add(mainPanel, BorderLayout.SOUTH);
add(tastybois, BorderLayout.EAST);
pack();
setVisible(true);
}
private void buildButtons(){
mainPanel = new JPanel();
calcButton = new JButton("Order");
exitButton = new JButton("Cancel");
calcButton.addActionListener(new CalcButtonListener());
exitButton.addActionListener(new ExitButtonListener());
mainPanel.add(calcButton);
mainPanel.add(exitButton);
}
private class CalcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double subtotal = 0.0;
double tax = 0.0;;
double total = 0.0;
subtotal = Dish.getDishPrice() +
drinks.getDrinkPrice() +
Side.getSidePrice();
tax = subtotal * taxRate;
total = subtotal + tax;
DecimalFormat dollar = new DecimalFormat("0.00");
JOptionPane.showMessageDialog(null, "Subtotal: $" + dollar.format(subtotal) + "\n" + "Tax: $" + dollar.format(tax) + "\n" + "Total: $" + dollar.format(total));
}
}
private class ExitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
}
Usually with a second JPanel so you have a hierarchy such your main JPanel (called container here) holds 5 other JPanels trough BorderLayout, on each sub-panel you set a new LayoutManager and add the components to it.
I'm trying to make this application to calculate but it won't. Spend ages on it. I just want to calculate ones I press the button. I need it to display the correct price when clicking on the correct combo box. The prices have been set I think.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class retailsalescalcu extends JFrame {
//create the objects
JLabel department;
JLabel number;
JLabel name;
JLabel price;
JLabel discount;
JLabel sale;
JComboBox<String> dept;
JTextField itemNum;
JTextField itemName;
JTextField itemPrice;
JTextField itemDisc;
JTextField salePrice;
JButton calculate;
JButton clear;
public retailsalescalcu() {
//set object variables
super("Retail Sales Calculator"); //set window bar title
setSize(300, 300); //set window size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set window close
GridLayout grid = new GridLayout(7, 2);
setLayout(grid);
department = new JLabel("Department");
dept = new JComboBox<String>();
dept.addItem("Select");
dept.addItem("Men's Clothing");
dept.addItem("Women's Clothing");
dept.addItem("Shoes");
dept.addItem("Belts");
dept.addItem("Electronics");
dept.addItem("Hats");
//add ItemListener - JTextField & ComboBox
dept.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
String str = (String)dept.getSelectedItem();
itemNum.setText(str);
} //end public void
}); //end item listener
number = new JLabel("Item Number");
itemNum = new JTextField(10);
name = new JLabel("Item Name");
itemName = new JTextField(10);
price = new JLabel("Original Price");
itemPrice = new JTextField(10);
discount = new JLabel("Discount");
itemDisc = new JTextField(10);
sale = new JLabel("Sale Price");
salePrice = new JTextField(10);
salePrice.setEditable(false);
calculate = new JButton("Calculate");
clear = new JButton("Clear");
//add objects to JFrame
add(department);
add(dept);
add(number);
add(itemNum);
add(name);
add(itemName);
add(price);
add(itemPrice);
add(discount);
add(itemDisc);
add(sale);
add(salePrice);
add(calculate);
add(clear);
//add event listener to calculate sale price
calculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent retail) {
String input1;
String input2;
double origPrice;
double percOff;
double clearance;
input1 = itemPrice.getText();
input2 = itemDisc.getText();
origPrice = Double.parseDouble(input1);
percOff = Double.parseDouble(input2)/100;
clearance = origPrice - (origPrice * percOff);
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
salePrice.setText(df.toString()); //output to JTextField
}
});
//add event listener to reset fields
clear.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent event) { //JButton event if clicked
dept.setSelectedIndex(0); //Combo Box will be empty and can be reset
itemNum.setText(null); //Item Number will be empty and can be reset
itemName.setText(null); //Item Name will be empty and can be reset
itemPrice.setText(null); //Item Price will be empty and can be reset
itemDisc.setText(null); //Item Discount will be empty and can be reset
salePrice.setText(null); //Item SalePrice will be empty and can be reset
}
});
setVisible(true);
} //end public retailsalescalcu
public static void main(String[] args) {
new retailsalescalcu();
} //end public static void
} //end public class retailsalescalcu
After debugging you code i found that you should remove/comment line #100 from your code
From
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
salePrice.setText(df.toString()); //output to JTextField
System.err.println(df.toString());
}
});
to
DecimalFormat df = new DecimalFormat("$#,###.##");
df.format(clearance);
salePrice.setText(df.format(clearance));
//salePrice.setText(df.toString()); //output to JTextField
System.err.println(df.toString());
}
});
EDIT:
One problem is here:
//salePrice.setText(df.toString());
Comment that out and you will see your price after clicking Calculate. You are already setting salesPrice here:
salePrice.setText(df.format(clearance));
The toString() is not going to give you what you want.
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));
So here is my question:
I would like to create a new panel that asks the user to enter Bank Account Information (Account Name, and Account Number) and when the user clicks on the Login button, it changes panels to the Withdraw/Deposit Panel and also displays your Account Name at the top. I have the Withdraw/Deposit Panel all completed, but am stumped on how to create the Information Panel and to make it appear BEFORE the Withdraw/Deposit Panel, etc.
Here is my code:
public class MyFrame extends JFrame {
private JPanel panel;
private JLabel wordsLabel;
private JLabel balanceLabel;
private JLabel choiceLabel;
private JTextField transactionAmount;
private JRadioButton depositButton;
private JRadioButton withdrawButton;
private double balance;
public MyFrame() {
final int FIELD_WIDTH = 5;
balance = 500;
panel = new JPanel();
wordsLabel = new JLabel();
balanceLabel = new JLabel();
choiceLabel = new JLabel();
transactionAmount = new JTextField(FIELD_WIDTH);
JPanel buttonPanel = new JPanel();
ButtonGroup myGroup = new ButtonGroup();
depositButton = new JRadioButton("Deposit");
withdrawButton = new JRadioButton("Withdraw");
transactionAmount.setText("0");
wordsLabel.setText("Welcome to Wes Banco! Your current balance is: ");
balanceLabel.setText(String.format("%10.2f", balance));
choiceLabel.setText("How much would you like to deposit/withdraw? ");
panel.setLayout(new GridLayout(4, 4, 5, 10));
panel.add(wordsLabel);
panel.add(balanceLabel);
panel.add(choiceLabel);
panel.add(transactionAmount);
myGroup.add(depositButton);
myGroup.add(withdrawButton);
buttonPanel.add(depositButton);
buttonPanel.add(withdrawButton);
ButtonListener myListener = new ButtonListener();
depositButton.addActionListener(myListener);
withdrawButton.addActionListener(myListener);
panel.add(buttonPanel);
this.add(panel);
}
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
double amount = Double.parseDouble(transactionAmount.getText());
if (amount == 0) {
JOptionPane.showMessageDialog(null,
"You cannot deposit or withdraw nothing!");
JOptionPane.showMessageDialog(null,
"Please enter a valid amount.");
} else {
if (event.getSource() == depositButton) {
JOptionPane.showMessageDialog(null,
"You have deposited: " + amount);
balance += amount;
} else if (event.getSource() == withdrawButton) {
if (balance < amount) {
JOptionPane.showMessageDialog(null,
"You do not have sufficient funds to complete this transaction.");
JOptionPane.showMessageDialog(null,
"Please enter a valid amount.");
} else {
JOptionPane.showMessageDialog(null,
"You have withdrawn: " + amount);
balance -= amount;
}
}
balanceLabel.setText(String.valueOf(balance));
}
}
}
}
My advice would be: DonĀ“t create the panel in your JFrame constructor. Make an InfoPanel class and a WithdrawPanel class. Then you can decide programatically which panel is displayed in your frame.
I'm trying to write a program that will take text in a JTextField and put it into variables I've declared when I press a JButton. I need to calculate weekly pay for a school project, but that only requires the console, I'm doing the GUI for my own fun. I'm trying to get it so when I hit 'calc' it'll take the imputs from id, rh, oh, hp, etc and calculate weekly pay (wp), which will then be printed on the right column next to the calc button.
//the calculations aren't complete yet until I finish the GUI
public class Weekly_Pay
{
public static void calculations(String[] args)
{
Scanner imput = new Scanner(System.in);
System.out.println("ID number: ");
int employeeId = imput.nextInt();
System.out.println("Hourly Wage: ");
Double hourlyWage = imput.nextDouble();
System.out.println("Regular Hours: ");
double regularHours = imput.nextDouble();
System.out.println("Overtime Hours: ");
double overtimeHours = imput.nextDouble();
double overtimePay = round(overtimeHours * (1.5 * hourlyWage));
double regularPay = round(hourlyWage * regularHours);
double weeklyPay = regularPay + overtimePay;
System.out.println("Employee ID Number:" + employeeId);
System.out.printf("Weekly Pay: " + "$%.2f\n", weeklyPay);
}
public static double round(double num)
{
// rounding to two decimal places
num *= 100;
int rounded = (int) Math.round(num);
return rounded/100.0;
}
public static void main(String[] args)
{
JFrame window = new JFrame();
window.setTitle("Weekly Pay");
window.setSize(350, 200);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Color lGray = new Color(209, 209, 209);
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setBackground(lGray);
panel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
JTextField idEntry = new JTextField(); //where the user imputs their ID
JTextField hwEntry = new JTextField(); //where the user imputs their hourly wage
JTextField rhEntry = new JTextField(); //where the user imputs their regular hours
JTextField ohEntry = new JTextField(); //where the user imputs their overtime hours
JLabel id = new JLabel("ID Number");
JLabel hw = new JLabel("Hourly Wage");
JLabel rh = new JLabel("Regular Hours");
JLabel oh = new JLabel("Overtime Hours");
JButton calc = new JButton("Calculate");
JLabel wp = new JLabel(" Weekly Pay: $" + "$%.2f\n", weeklyPay);
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
hGroup.addGroup(layout.createParallelGroup().
addComponent(id).addComponent(hw).addComponent(rh).addComponent(oh).addComponent(calc));
hGroup.addGroup(layout.createParallelGroup().
addComponent(idEntry).addComponent(hwEntry).addComponent(rhEntry).addComponent(ohEntry).addComponent(wp));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(id).addComponent(idEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(hw).addComponent(hwEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(rh).addComponent(rhEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(oh).addComponent(ohEntry));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(calc).addComponent(wp));
layout.setVerticalGroup(vGroup);
window.add(panel);
window.setVisible(true);
}
}
for example:
String input = new String();
JButton mbutt = new JButton;
JTextField jtxt = new JTextField();
mbutt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
input = jtxt.getText().toString();
}
});
////////////////////////////////// Edited Part //////////////////////////////
Now few things before i jump into the code.
- I just wanted to show the working of ActionListener, and how to extract a data from a field and put it into a variable.
- Its a bad practice to directly put the component on the JFrame, and thats exactly what i have done here (too bad of me..!!!), so You should always use something like a JPanel over the JFrame, and then place the component over it. In order to keep it Simple i have Deliberately use direct JFrame to hold the components.
- And yes, Its always a very good practice to have the UI work on the UI thread, and Non-UI work on Non-UI thread.
- In Swings main() method is Not long lived, after scheduling the construction of GUI in the Event Dispatcher Thread it exits... So now its the responsibility of EDT to handle the GUI, so you should keep the EDT for handling the GUI only, as i have done it in the main() method [EventQueue.invokeLater()].
Full Code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Tes extends JFrame {
String input;
JTextField jtxt;
JButton mbutt;
public Tes(){
//--ALWAYS USE A JPANEL OVER JFRAME, I DID THIS TO KEEP IT SIMPLE FOR U--//
this.setSize(400,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setComponent();
this.setHandler();
}
public void setComponent(){
jtxt = new JTextField("Hello");
mbutt = new JButton("Button");
this.add(BorderLayout.SOUTH,mbutt);
this.add(BorderLayout.NORTH,jtxt);
}
public void setHandler(){
mbutt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
input = jtxt.getText().toString();
System.out.println("Input Value: "+input);
**//--See your Console Output everytime u press the button--//**
}
});
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
#Override
public void run() {
Tes t = new Tes();
t.setVisible(true);
}
});
}
}