JAVA GUI won't calculate the price - java

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.

Related

JOptionpane.showMessageDialog not working inside of if-statement (event handler Program)

Context
I'm trying to build a percentage calculator using JFrame and event handling by having blank text fields and "enter" buttons and displaying the answer depending on which button they click (two different calculations for each button).
Problem
Thing is, when I put the JOptionPane.showMessageDialog line inside of the if/else if statement (all in the actionPerformed method), the program runs, but clicking the buttons does nothing. But if I put it outside of the statements, it says the answer variable is undeclared.
I realize a percentage calculator can be done in a million other, simpler ways, but this is simply what I had in mind and wanted to see if I could do it (I'm a complete beginner).
Code
public class PercentageCalc extends JFrame{
private JTextField item2, item4, item5, item7;
private JButton button, button2;
public PercentageCalc(){
super("Percentage Calculator");
setLayout(new FlowLayout());
JLabel item1 = new JLabel("What is");
add(item1);
JTextField item2 = new JTextField(3);
add(item2);
JLabel item3 = new JLabel("% of");
add(item3);
JTextField item4 = new JTextField(2);
add(item4);
button = new JButton("Enter");
add(button);
JLabel spacer = new JLabel(" ");
add(spacer);
JTextField item5 = new JTextField(3);
add(item5);
JLabel item6 = new JLabel("is what % of");
add(item6);
JTextField item7 = new JTextField(3);
add(item7);
button2 = new JButton("Enter");
add(button2);
thehandler handler = new thehandler();
button.addActionListener(handler);
button2.addActionListener(handler);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent e){
String strx;
String stry;
double x, y, answer;
if(e.getSource()==button){
strx = item2.getText();
stry = item4.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = y * 0.01 * x;
JOptionPane.showMessageDialog(null, answer);
}
else if(e.getSource()==button2){
strx = item5.getText();
stry = item7.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = x/y*100;
JOptionPane.showMessageDialog(null, answer);
}
}
You have member-variable and local variable with the same name. Please read ere and here about it.
Here is the corrected variant of you program
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class PrecentageCalc extends JFrame {
private JTextField item2, item4, item5, item7;
private JButton button, button2;
public PrecentageCalc() {
super("Percentage Calculator");
setLayout(new FlowLayout());
JLabel item1 = new JLabel("What is");
add(item1);
item2 = new JTextField(3);
add(item2);
JLabel item3 = new JLabel("% of");
add(item3);
item4 = new JTextField(2);
add(item4);
button = new JButton("Enter");
add(button);
JLabel spacer = new JLabel(" ");
add(spacer);
item5 = new JTextField(3);
add(item5);
JLabel item6 = new JLabel("is what % of");
add(item6);
item7 = new JTextField(3);
add(item7);
button2 = new JButton("Enter");
add(button2);
thehandler handler = new thehandler();
button.addActionListener(handler);
button2.addActionListener(handler);
}
private class thehandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String strx;
String stry;
double x, y, answer;
if (e.getSource() == button) {
strx = item2.getText();
stry = item4.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = y * 0.01 * x;
JOptionPane.showMessageDialog(null, answer);
} else if (e.getSource() == button2) {
strx = item5.getText();
stry = item7.getText();
x = Double.parseDouble(strx);
y = Double.parseDouble(stry);
answer = x / y * 100;
JOptionPane.showMessageDialog(null, answer);
}
}
}
public static void main(String[] args) {
JFrame frm = new PrecentageCalc();
frm.pack();
frm.setLocationRelativeTo(null);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setVisible(true);
}
}
Use separate ActionListeners for your buttons. Both use the same calculation method with different parameters:
public PercentageCalc() {
// Part of your code
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
handleInput(item2.getText(), item4.getText());
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
handleInput(item5.getText(), item7.getText());
}
});
}
private void handleInput(final String strx, final String stry) {
final double x = Double.parseDouble(strx);
final double y = Double.parseDouble(stry);
final double answer = y * 0.01 * x;
JOptionPane.showMessageDialog(null, answer);
}

Remove Java Panels without crashing your program

So basically I am writing a GUI program that uses a JComboBox to display various finance formulas. I have everything in place in terms of it displaying the formulas but here is my problem. Everytime I go to choose a new formula in my comboBox it the other ones stay displayed. I've tried to write an if statement to disable, remove and invalidate these (not all at once) but none have worked...I need to get it so when I click a option the other panels disappear if there are any at all. Thanks!
Here is the full program the problem I am having is that when I choose a new formula the one that I chose before it is still active...I want to disable or remove it. Thanks.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class newFinanceFullClass extends JFrame {
private JMenu fileMenu;
private JMenuItem exitItem;
private JPanel presentValuePanel;
private JPanel financeFinderPanel;// A panel container
private JLabel principalMessage;
private JLabel yearlyRateMessage;
private JLabel termYearMessage;
private JPanel simpleInterestPanel;
private JPanel doublingTimePanel;
private JPanel compoundInterestPanel;
private JLabel NONEMessage;
private JLabel imageLabel;
private JLabel label;// A message to display
private JMenuBar menuBar;
private JTextField principalText; // To hold user input
private JButton calcButton; // Performs calculation
private final int WINDOW_WIDTH = 600; // Window width
private final int WINDOW_HEIGHT = 600; // Window height
private JTextField yearlyRateText;
private JTextField termYearText;
DecimalFormat dc =new DecimalFormat("####0.00"); //formater
private JComboBox financeBox;
double principal = 400.0;
double yearlyRate = .04;
double termYears = 4.0;
private String[] financeFormulas = { "NONE", "Present value", "Simple interest",
"Doubling time", "Compound interest", "Decaf"};
financeFormulaClass financeFormula = new financeFormulaClass(principal, yearlyRate, termYears);
/**
* Constructor
*/
public newFinanceFullClass()
{
// Call the JFrame constructor.
super("Finance Class");
// Set the size of the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
// Specify what happens when the close
// button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel and add it to the frame.
financeFinderPanel();
setLayout(new BorderLayout());
//buildPanel();
menuBar = new JMenuBar();
buildFileMenu();
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Add the panel to the frame's content pane.
add(financeFinderPanel);
//add(panel);
// Display the window.
setVisible(true);
}
private void financeFinderPanel()
{
// Create a panel to hold the combo box.
financeFinderPanel = new JPanel();
//create label
label = new JLabel("Pick your formula");
ImageIcon funnyImage = new ImageIcon("funny.gif");
imageLabel = new JLabel();
imageLabel.setLocation(50, 55);
label.setForeground(Color.BLUE);
// Create the combo box
financeBox = new JComboBox(financeFormulas);
imageLabel.setIcon(funnyImage);
// Register an action listener.
financeBox.addActionListener(new financeBoxListener());
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
// Add the combo box to the panel.
financeFinderPanel.add(financeBox);
financeFinderPanel.add(label);
financeFinderPanel.add(imageLabel);
}
/** private void menuList(){
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
menuList.add(exitItem);
} **/
private void buildMenuBar()
{
// Create the menu bar.
menuBar = new JMenuBar();
// Create the file and text menus.
buildFileMenu();
// buildTextMenu();
// Add the file and text menus to the menu bar.
menuBar.add(fileMenu);
//menuBar.add(textMenu);
// Set the window's menu bar.
setJMenuBar(menuBar);
}
private void buildFileMenu()
{
// Create an Exit menu item.
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
exitItem.addActionListener(new ExitListener());
// Create a JMenu object for the File menu.
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
// Add the Exit menu item to the File menu.
fileMenu.add(exitItem);
}
private void presentValuePanel()
{
// Create the label, text field, and button components.
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Present Value");
// Add an action listener to the button.
//calcButton.addActionListener(new CalcButtonListener());
calcButton.addActionListener(new financeFormListener());
// Create a panel to hold the components.
presentValuePanel = new JPanel();
// Add the label, text field, and button to the panel.
presentValuePanel.add(principalMessage);
presentValuePanel.add(principalText);
presentValuePanel.add(yearlyRateMessage);
presentValuePanel.add(yearlyRateText);
presentValuePanel.add(termYearMessage);
presentValuePanel.add(termYearText);
presentValuePanel.add(calcButton);
}
private void simpleInterestPanel(){
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Simple Interest");
simpleInterestPanel = new JPanel();
calcButton.addActionListener(new financeFormListener());
simpleInterestPanel.add(principalMessage);
simpleInterestPanel.add(principalText);
simpleInterestPanel.add(yearlyRateMessage);
simpleInterestPanel.add(yearlyRateText);
simpleInterestPanel.add(termYearMessage);
simpleInterestPanel.add(termYearText);
simpleInterestPanel.add(calcButton);
}
private void doublingTimePanel(){
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
calcButton = new JButton("Calc Doubling Time");
calcButton.addActionListener(new financeFormListener());
doublingTimePanel = new JPanel();
doublingTimePanel.add(yearlyRateMessage);
doublingTimePanel.add(yearlyRateText);
doublingTimePanel.add(calcButton);
}
private void compoundInterestPanel(){
principalMessage = new JLabel("principal");
principalText = new JTextField(10);
yearlyRateMessage = new JLabel("Yearly Rate");
yearlyRateText = new JTextField(10);
termYearMessage = new JLabel("Term Year");
termYearText = new JTextField(10);
calcButton = new JButton("Calc Compound Interest");
compoundInterestPanel = new JPanel();
calcButton.addActionListener(new financeFormListener());
compoundInterestPanel.add(principalMessage);
compoundInterestPanel.add(principalText);
compoundInterestPanel.add(yearlyRateMessage);
compoundInterestPanel.add(yearlyRateText);
compoundInterestPanel.add(termYearMessage);
compoundInterestPanel.add(termYearText);
compoundInterestPanel.add(calcButton);
}
//Listener to choose which formula
private class financeBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object actionCommand = e.getSource();
String selection = (String) financeBox.getSelectedItem();
if(selection.equals("Present value")){
//financeFinderPanel.removeAll();
presentValuePanel();
add(presentValuePanel, BorderLayout.SOUTH);
pack();
}
else if(selection.equals("Simple interest")){
simpleInterestPanel();
add(simpleInterestPanel, BorderLayout.NORTH);
pack();
}
else if(selection.equals("Doubling time")){
doublingTimePanel();
add(doublingTimePanel, BorderLayout.SOUTH);
pack();
}
else if(selection.equals("Compound interest")){
compoundInterestPanel();
add(compoundInterestPanel, BorderLayout.NORTH);
pack();
}
else if(selection.equals("NONE")){
setSize(200, 150);
financeFinderPanel();
add(financeFinderPanel, BorderLayout.NORTH);
NONEMessage = new JLabel("PICK A SELECTION");
}
}
}
private class financeFormListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Calc Simple Interest")){
try{
double principal = Double.parseDouble(principalText.getText());
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double termYears = Double.parseDouble(termYearText.getText());
double interestRate = (principal * yearlyRate * termYears);
String msg = "Simple interest is: $" + dc.format(interestRate);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
else if(actionCommand.equals("Calc Present Value"))
{
try{
double principal = Double.parseDouble(principalText.getText());
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double termYears = Double.parseDouble(termYearText.getText());
double pValue = financeFormula.presentValue(principal, yearlyRate, termYears);
//double pValue = principal * (((1- Math.pow(1 + yearlyRate, -termYears))/ yearlyRate));
String msg = "Present value is: $" + dc.format(pValue);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
else if(actionCommand.equals("Calc Doubling Time")){
try{
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double dValue = financeFormula.doublingTime(yearlyRate);
String msg = "Doubling Time is: " + dc.format(dValue);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
else if(actionCommand.equals("Calc Compound Interest")){
try{
double principal = Double.parseDouble(principalText.getText());
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double termYears = Double.parseDouble(termYearText.getText());
double compoundInterest = financeFormula.compoundInterest(principal, yearlyRate, termYears);
String msg = "Compound Interest is: $" + dc.format(compoundInterest);
JOptionPane.showMessageDialog(null, msg);
}
catch(NumberFormatException r){
JOptionPane.showMessageDialog(null, "Please insert formula information");
}
}
}
}
private class ExitListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
new newFinanceFullClass();
}
}
Again, use a CardLayout to help you swap your JPanels. You would create a JPanel and set its layout to CardLayout, and then you'd add the JPanels (the "cards") that you wish to swap into this holder JPanel using String constants, Strings that you will pass into the CardLayout's show(...) method to allow it to swap your components.
For instance, say you had an enum to hold your financial formula Strings, something like:
public enum FinanceFormula {
NONE("NONE"),
PRESENT_VALUE("Present value"),
SIMPLE_INTEREST("Simple interest"),
DOUBLING_TIME("Doubling time"),
COMPOUND_INTEREST("Compound interest"),
DECAF("Decaf");
private String name;
private FinanceFormula(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return getName();
};
}
Then the CardLayout and its JPanel could be set up like so:
private CardLayout cardLayout = new CardLayout();
private JPanel cardHolderPanel = new JPanel(cardLayout);
and the JComboBox like below. This works because I have overridden the enum's to String method so that a proper name will display:
private JComboBox<FinanceFormula> comboBox = new JComboBox<>(FinanceFormula.values());
You would then add all the formula JPanels into the cardHolderPanel using String constants obtained from the enum:
// fill the cardHolderPanel with "cards", JPanels with formula:
cardHolderPanel.add(createNonePanel(), FinanceFormula.NONE.getName());
cardHolderPanel.add(createPresentValuePanel(), FinanceFormula.PRESENT_VALUE.getName());
cardHolderPanel.add(createSimpleInterestPanel(), FinanceFormula.SIMPLE_INTEREST.getName());
cardHolderPanel.add(createDoublingTimePanel(), FinanceFormula.DOUBLING_TIME.getName());
cardHolderPanel.add(createCompoundInterestPanel(), FinanceFormula.COMPOUND_INTEREST.getName());
cardHolderPanel.add(createDecafPanel(), FinanceFormula.DECAF.getName());
Then when you want to swap JPanels, simply pass in the appropriate String into the CardLayout's show method, and you're good:
private void combBoxActionPerformed(ActionEvent e) {
FinanceFormula selectedFormula = (FinanceFormula) comboBox.getSelectedItem();
cardLayout.show(cardHolderPanel, selectedFormula.getName());
}
The following program doesn't create any fancy formula JPanels, but it doesn't have to, since it is an MCVE built to demonstrate swapping JPanels only:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class NewFinance2 extends JPanel {
private CardLayout cardLayout = new CardLayout();
private JPanel cardHolderPanel = new JPanel(cardLayout);
private JComboBox<FinanceFormula> comboBox = new JComboBox<>(FinanceFormula.values());
public NewFinance2() {
// fill the cardHolderPanel with "cards", JPanels with formula:
cardHolderPanel.add(createNonePanel(), FinanceFormula.NONE.getName());
cardHolderPanel.add(createPresentValuePanel(), FinanceFormula.PRESENT_VALUE.getName());
cardHolderPanel.add(createSimpleInterestPanel(), FinanceFormula.SIMPLE_INTEREST.getName());
cardHolderPanel.add(createDoublingTimePanel(), FinanceFormula.DOUBLING_TIME.getName());
cardHolderPanel.add(createCompoundInterestPanel(), FinanceFormula.COMPOUND_INTEREST.getName());
cardHolderPanel.add(createDecafPanel(), FinanceFormula.DECAF.getName());
comboBox.addActionListener(e -> combBoxActionPerformed(e));
JPanel northPanel = new JPanel();
northPanel.add(comboBox);
setLayout(new BorderLayout());
add(cardHolderPanel, BorderLayout.CENTER);
add(northPanel, BorderLayout.NORTH);
}
private void combBoxActionPerformed(ActionEvent e) {
FinanceFormula selectedFormula = (FinanceFormula) comboBox.getSelectedItem();
cardLayout.show(cardHolderPanel, selectedFormula.getName());
}
// A bunch of dummy methods that don't create much
// Your real methods would create more complex JPanels
private JPanel createDecafPanel() {
return createPanel(FinanceFormula.DECAF);
}
private JPanel createCompoundInterestPanel() {
return createPanel(FinanceFormula.COMPOUND_INTEREST);
}
private JPanel createDoublingTimePanel() {
return createPanel(FinanceFormula.DOUBLING_TIME);
}
private JPanel createSimpleInterestPanel() {
return createPanel(FinanceFormula.SIMPLE_INTEREST);
}
private JPanel createPresentValuePanel() {
return createPanel(FinanceFormula.PRESENT_VALUE);
}
private JPanel createNonePanel() {
return createPanel(FinanceFormula.NONE);
}
// temporary method just for demonstration purposes
private JPanel createPanel(FinanceFormula financeFormula) {
JLabel label = new JLabel(financeFormula.getName());
label.setFont(label.getFont().deriveFont(Font.BOLD, 24f));
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setPreferredSize(new Dimension(400, 300));
float split = 0.7f;
float h = (float) (split + Math.random() * (1f - split));
float s = (float) (split + Math.random() * (1f - split));
float b = (float) (split + Math.random() * (1f - split));
Color color = Color.getHSBColor(h, s, b);
panel.setBackground(color);
return panel;
}
private static void createAndShowGui() {
NewFinance2 mainPanel = new NewFinance2();
JFrame frame = new JFrame("Finance");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

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

Using JTextField for user input

Thanks for your help guys...now the program works and runs like it should.. but I have 2 more question.
1.How can I get the output into a JTestField t4 or t5
2.How can I close the application using the JButton Buton3
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TriangleFarfan{
JFrame Triangle = new JFrame("Triangle Calculator");
JButton Button1 = new JButton ("Area");
JButton Button2 = new JButton("Perimeter");
JButton Button3 = new JButton("Close");
JTextField t1 = new JTextField(20);
String t1TextBox = t1.getText();
double side1 = Double.parseDouble(t1TextBox);
JPanel j1 = new JPanel (new FlowLayout());
JLabel l1 = new JLabel("Enter side 1:");
JTextField t2 = new JTextField();
String t2TextBox = t2.getText();
double side2 = Double.parseDouble(t2TextBox);
JPanel j2 = new JPanel (new FlowLayout());
JLabel l2 = new JLabel("Enter side 2:");
JTextField t3 = new JTextField();
String t3TextBox = t3.getText();
double side3 = Double.parseDouble(t3TextBox);
JPanel j3 = new JPanel (new FlowLayout());
JLabel l3 = new JLabel("Enter side 3:");
JTextField t4 = new JTextField();
JPanel j4 = new JPanel (new FlowLayout());
JLabel l4 = new JLabel("Area Result");
JTextField t5 = new JTextField(20);
JPanel j5 = new JPanel (new FlowLayout());
JLabel l5 = new JLabel("Perimeter Result");
public TriangleFarfan()
{
j1.add(l1);
j1.add(t1);
j2.add(l2);
j2.add(t2);
j3.add(l3);
j3.add(t3);
j4.add(l4);
j4.add(t4);
j5.add(l5);
j5.add(t5);
Triangle.add(j1);
Triangle.add(j2);
Triangle.add(j3);
Triangle.add(j4);
Triangle.add(j5);
Triangle.add(Button1);
Button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
double Area = (side1 * side2)/2;
//Execute when button is pressed
System.out.println(Area);
}
});
Triangle.add(Button2);
Button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the Perimeter Button");
}
});
Triangle.add(Button3);
Button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the Close Button");
}
});
Triangle.setLayout(new FlowLayout());
Triangle.setSize(450,400);
Triangle.setVisible(true);
Triangle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
In addition to missing a main method, as Reimeus pointed out, your order of instructions is wrong. You are trying to read the user input before anything is even shown on the screen, and even before an object is created. For example, this line:
String t1TextBox = t1.getText();
tries to obtain a text from a TextBox that wasn't even added to a Panel that wasn't yet created.
To solve this, you need to rethink the logic of your program. Here are a few hints:
avoid assignments outside methods. Instead of writing
JFrame Triangle = new JFrame("Triangle Calculator");
declare the variable in the class body like this:
JFrame Triangle;
and assign it inside the constructor like this:
Triangle = new JFrame("Triangle Calculator");
Build the whole UI, then worry about listeners. This way you can be sure that you are not referencing an UI element that does not exist when getting the user input.
Get the user input inside the listeners, like this:
Button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// get the size of side1 from the textbox
String t1TextBox = t1.getText();
double side1 = Double.parseDouble(t1TextBox);
// get the size of side2 from the textbox
String t2TextBox = t2.getText();
double side2 = Double.parseDouble(t2TextBox);
// now we can calculate the area
double Area = (side1 * side2)/2;
//Execute when button is pressed
System.out.println(Area);
}
});
Add a main method:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TriangleFarfan();
}
});
}
The declaration
JTextField t1 = new JTextField(20);
doesn't set the value in the JTextField to 20. Instead it sets the number of columns for the JTextComponent but with an empty String. Therefore the line
double side1 = Double.parseDouble(t1TextBox);
will throw an NumberFormatException on startup.

Make JButton insert text from JTextField into variables?

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

Categories

Resources