having errors in a java function - java

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
/**
Grocery shop class
*/
public class Grocery_shop extends JFrame
{
private Grocery_items items; // A panel for routine charge checkboxes
private quantitypanel qty; // A panel for quantity
private JPanel buttonPanel; // A panel for the buttons
private JButton calcButton; // Calculates everything
private JButton exitButton; // Exits the application
/**
Constructor
*/
public Grocery_shop()
{
// Display a title.
setTitle("Victor's Grocery Shop");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a NonRoutinePanel object.
qty = new quantitypanel();
// qty.setBackground(Color.white);
// Create a RoutinePanel object.
items = new Grocery_items(qty);
// Build the panel that contains the buttons.
buildButtonPanel();
// Add the panels to the content pane.
add(items, BorderLayout.WEST);
add(qty, BorderLayout.EAST);
add(buttonPanel, BorderLayout.SOUTH);
// Pack and display the window.
pack();
setVisible(true);
}
/**
The buildButtonPanel method creates a panel containing
buttons.
*/
private void buildButtonPanel()
{
// Create a button to calculate the charges.
calcButton = new JButton("Add Charges");
// Add an action listener to the button.
calcButton.addActionListener(new CalcButtonListener());
// Create a button to exit the application.
exitButton = new JButton("Exit");
// Add an action listener to the button.
exitButton.addActionListener(new ExitButtonListener());
// Put the buttons in their own panel.
buttonPanel = new JPanel();
buttonPanel.add(calcButton);
buttonPanel.add(exitButton);
}
/**
CalcButtonListener is an action listener class for the
calcButton component.
*/
private class CalcButtonListener implements ActionListener
{
/**
actionPerformed method
#param e An ActionEvent object.
*/
public void actionPerformed(ActionEvent e)
{
double totalCharges; // Total charges
// Create a DecimalFormat object to format output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Calculate the total charges
totalCharges = items.getCharges();
//+ nonRoutine.getCharges();
// Display the message.
JOptionPane.showMessageDialog(null, "Total Charges: $" +
dollar.format(totalCharges));
}
} // End of inner class
/**
ExitButtonListener is an action listener class for the
exitButton component.
*/
private class ExitButtonListener implements ActionListener
{
/**
actionPerformed method
#param e An ActionEvent object.
*/
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
} // End of inner class
/**
The main method creates an instance of the JoesAutomotive
class, causing it to display its window.
*/
public static void main(String[] args)
{
Grocery_shop grocery = new Grocery_shop();
}
}
import java.awt.*;
import javax.swing.*;
import java.text.DecimalFormat;
/**
RoutinePanel class
*/
public class Grocery_items extends JPanel
{
// Named constants for charges
private final double Baked_Beans = 0.35;
private final double Cornflakes = 1.75;
private final double Sugar = 0.75;
private final double Tea_Bags = 1.15;
private final double Instant_Coffee = 2.50;
private final double Bread = 1.25;
private final double Sausage = 1.30;
private final double Eggs = 0.75;
private final double Milk = 0.65;
private final double Potatoes = 2.00;
// private quantitypanel qty; // A panel for quantity
private JCheckBox baked_beans_box; // Check box for baked_beans
private JCheckBox CornflakesBox; // Check box for cornflakes
private JCheckBox SugarBox; // Check box for sugar box
private JCheckBox Tea_Bags_Box; // Check box for tea bag
private JCheckBox Instant_Coffee_Box; // Check box for Instant_Coffee_Box
private JCheckBox Bread_Box; // Check box for bread box
private JCheckBox SausageBox; // Check box for sausage box
private JCheckBox eggbox; // Check box for egg box
private JCheckBox milkbox; // Check box for milk
private JCheckBox potatoesbox; // Check box for potatoes
// private JTextField baked_beans_JT;
/**
Constructor
*/
public Grocery_items(quantitypanel qty)
{
this.qty = qty;
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Create the check boxes.
baked_beans_box = new JCheckBox("Baked_Beans ($" +
dollar.format(Baked_Beans) + ")");
CornflakesBox = new JCheckBox("Cornflakes ($" +
dollar.format(Cornflakes) + ")");
SugarBox = new JCheckBox("Sugar ($" +
dollar.format(Sugar) + ")");
Tea_Bags_Box = new JCheckBox("Tea Bags ($" +
dollar.format(Tea_Bags) + ")");
Instant_Coffee_Box = new JCheckBox("Instant Coffee_Box ($" +
dollar.format(Instant_Coffee) + ")");
Bread_Box = new JCheckBox("Bread Box ($" +
dollar.format(Bread) + ")");
SausageBox = new JCheckBox("Suasages ($" +
dollar.format(Sausage) + ")");
eggbox = new JCheckBox("Eggs ($" +
dollar.format(Eggs) + ")");
milkbox = new JCheckBox("Milk ($" +
dollar.format(Milk) + ")");
potatoesbox = new JCheckBox("Potatoes ($" +
dollar.format(Potatoes) + ")");
// Create a GridLayout manager.
setLayout(new GridLayout(10, 1));
// Create a border.
setBorder(BorderFactory.createTitledBorder("Grocery Items"));
// Add the check boxes to this panel.
add(baked_beans_box);
add(CornflakesBox);
add(SugarBox);
add(Tea_Bags_Box);
add(Instant_Coffee_Box);
add(Bread_Box);
add(SausageBox);
add(eggbox);
add(milkbox);
add(potatoesbox);
}
/**
The getCharges method calculates the routine charges.
#return The amount of routine charges.
*/
public double getCharges()
{
double charges = 0;
if (baked_beans_box.isSelected())
charges += Baked_Beans * qty.getBeanqty();
if (CornflakesBox.isSelected())
charges += Cornflakes;
if (SugarBox.isSelected())
charges += Sugar;
if (Tea_Bags_Box.isSelected())
charges += Tea_Bags;
if (Instant_Coffee_Box.isSelected())
charges += Instant_Coffee;
if (Bread_Box.isSelected())
charges += Bread;
if (SausageBox.isSelected())
charges += Sausage;
if (eggbox.isSelected())
charges += Eggs;
if (milkbox.isSelected())
charges += Milk;
if (potatoesbox.isSelected())
charges += Potatoes;
return charges;
}
}
//import java.awt.LayoutManager;
import java.awt.GridLayout;
//import javax.swing.JCheckBox;
//import javax.swing.JLabel;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class quantitypanel extends JPanel {
private JTextField baked_beans_JT; // JTextField box for baked_beans
private JTextField Cornflakes_JT; // JTextField box for cornflakes
private JTextField Sugar_JT; // JTextField box for sugar box
private JTextField Tea_Bags_JT; // JTextField box for tea bag
private JTextField Instant_Coffee_JT; // JTextField box for Instant_Coffee_Box
private JTextField Bread_JT; // JTextField box for bread box
private JTextField Sausage_JT; // JTextField box for sausage box
private JTextField egg_JT; // JTextField box for egg box
private JTextField milk_JT; // JTextField box for milk
private JTextField potatoes_JT; // JTextField box for potatoes
public quantitypanel()
{
//create JTextField.
baked_beans_JT = new JTextField(5);
Cornflakes_JT = new JTextField(5);
Sugar_JT = new JTextField(5);
Tea_Bags_JT = new JTextField(5);
Instant_Coffee_JT = new JTextField(5);
Bread_JT = new JTextField(5);
Sausage_JT = new JTextField(5);
egg_JT = new JTextField(5);
milk_JT = new JTextField(5);
potatoes_JT = new JTextField(5);
//initialize text field to 0
baked_beans_JT.setText("0");
Cornflakes_JT.setText("0");
Sugar_JT.setText("0");
Tea_Bags_JT.setText("0");
Instant_Coffee_JT.setText("0");
Bread_JT.setText("0");
Sausage_JT.setText("0");
egg_JT.setText("0");
milk_JT.setText("0");
potatoes_JT.setText("0");
public double getBeanqty(){
return Double.parseDouble(baked_beans_JT.getText());
}
//set Layout manager
setLayout(new GridLayout(10, 1));
//create border and panel title
setBorder(BorderFactory.createTitledBorder("Amount"));
//add text fields to the panel.
add(baked_beans_JT);
add(Cornflakes_JT);
add(Sugar_JT);
add(Tea_Bags_JT);
add(Instant_Coffee_JT);
add(Bread_JT);
add(Sausage_JT);
add(egg_JT);
add(milk_JT);
add(potatoes_JT);
}
}
i'm having problems with the items = new Grocery_items(qty);
so therefore in the code every place that got qty has an error message attached to it. Please help
When the baked beans check box is selected, i want the number inputted into the jtextfield (Beanqty) to be multiplied by the baked beans checkbox.
thanks.

There is a compile error in the Grocery_Items class. You've commented the qty field:
// private quantitypanel qty; // A panel for quantity
Remove the comment
private quantitypanel qty; // A panel for quantity
and you won't have any more error messages attached to it [qty].

Related

Is there a way to call a method from a separate class in a Java GUI?

I am working on a project for a class. The project asked me to create 3 classes, one parent and two children, with 3 methods in each. It then asked me to create a GUI that would calculate the sales tax based on a few fields, including text and radio buttons. In my head, I would call my methods to run if a certain radio button is clicked, ie if the Hybrid button is clicked, it'll run the toString from the Hybrid class. Can someone help me figure out how exactly to do this?
package projecttwo;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javafx.scene.control.ToggleGroup;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import projectTwo.Automobile;
import projectTwo.Electric;
import projectTwo.Hybrid;
/**
* CMIS242
* November 14, 2020
* Sabrina Riley
* This program computes the sales tax for a collection of automobiles
*/
public class ProjectTwo extends JFrame implements ActionListener {
/**
* #param args the command line arguments
*/
//Variable declaration
private String select;
private JFrame frame;
private JPanel panel;
private JLabel label, label2, label3, label4, label5;
private JFormattedTextField mmText, salesText, mpgText, weightText, compute;
private JButton button, button2, button3;
private JRadioButton hybrid, electric, other;
private ButtonGroup bg;
private JPanel radioPanel;
Automobile car = new Automobile();
public ProjectTwo() {
//initialize GUI
frame = new JFrame();
//HandlerClass handler = new HandlerClass();
//add compute sales tax button
button = new JButton("Compute Sales Tax");
button.setBounds(0,100,150,50);
add(button);
button.addActionListener(this);
//add display results button
button2 = new JButton("Display Results");
button2.setBounds(0,200, 150, 50);
button2.addActionListener(this);
//add clear fields button
button3 = new JButton("Clear Fields");
button3.setBounds(200,200, 150, 50);
button3.addActionListener(this);
//add text field to display results from compute sales button
compute = new JFormattedTextField();
compute.setBounds(200,100,150,50);
compute.setEditable(false);
//add all other text fields
mmText = new JFormattedTextField();
mmText.addKeyListener(null);
//mmText.addActionListener(this);
salesText = new JFormattedTextField();
mpgText = new JFormattedTextField();
weightText = new JFormattedTextField();
//add radio buttons to pick between hybrid, electric, and other
hybrid = new JRadioButton("Hybrid", true);
electric = new JRadioButton("Electric", false);
other = new JRadioButton("Other", false);
//group the radio buttons together
bg = new ButtonGroup();
bg.add(hybrid);
bg.add(electric);
bg.add(other);
//arrange buttons vertically
radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(3,1));
//radioPanel.setBounds(100,200,150,200);
radioPanel.add(hybrid);
radioPanel.add(electric);
radioPanel.add(other);
setContentPane(radioPanel);
pack();
//make them listen to clicks
hybrid.addActionListener(this);
electric.addActionListener(this);
other.addActionListener(this);
//label all text fields
label = new JLabel("Make and Model");
label.setBounds(0, 0, 100, 150);
label2 = new JLabel("Sales Price");
label3 = new JLabel("Automobile Type");
label4 = new JLabel("Miles Per Gallon");
label5 = new JLabel("Weight in Pounds");
//implement panel with all labels, text fields, buttons, and radio buttons
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
//panel.setLayout(GridLayout(0,2));
panel.setLayout(new GridLayout(0,2));
panel.setSize(500, 500);
panel.add(label);
panel.add(mmText);
panel.add(label2);
panel.add(salesText);
panel.add(hybrid);
panel.add(electric);
panel.add(other);
panel.add(label3);
panel.add(mpgText);
panel.add(label4);
panel.add(weightText);
panel.add(label5);
panel.add(button);
panel.add(compute);
panel.add(button2);
panel.add(button3);
panel.add(radioPanel);
//set frame dimensions
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Automobile Sales Tax Calculator");
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String user = mmText.getText();
String sales = salesText.getText();
String mpg = mpgText.getText();
String weight = weightText.getText();
this.clearFields();
e.getActionCommand();
if(e.getSource()==hybrid) {
System.out.println("car is a hybrid");
} else if (e.getSource()==electric){
System.out.println("car is electric");
} else
System.out.println("car is basic");
System.out.println(", " + user + sales + ", " + weight + ", " + mpg);
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void clearFields() {
mmText.setText(null);
salesText.setText(null);
mpgText.setText(null);
weightText.setText(null);
compute.setText(null);
hybrid.setSelected(false);
electric.setSelected(false);
other.setSelected(false);
}
public static void main(String[] args) {
// TODO code application logic here
new ProjectTwo();
}
}
package projectTwo;
/**
* CMIS242
* November 14, 2020
* Sabrina Riley
* This program computes the sales tax for a collection of automobiles
*/
public class Automobile {
protected String make;
protected String model;
protected double salesPrice;
protected double salesTax;
public Automobile() {
make = "brand";
model = "type";
}
//A constructor that allows the make and purchase price to be initialized
public Automobile(String make, String model, double salesPrice, double salesTax) {
this.make = make;
this.model = model;
this.salesPrice = salesPrice;
this.salesTax = salesTax;
}
//A method that returns the base sales tax computed as 5% of the sales price
public double salesTax() {
salesTax = salesPrice * 0.05;
return salesTax;
}
//A toString method that returns a string containing the make and model of the
//automobile, the sales price, and the sales tax
public String toString() {
return make + model + salesTax;
}
}
package projectTwo;
/**
* CMIS242
* November 14, 2020
* Sabrina Riley
* This program computes the sales tax for a collection of automobiles
*/
public class Hybrid extends Automobile {
protected int mpg;
protected double discount;
//A constructor that allows the make and purchase price to be initialized
public Hybrid(int mpg) {
super();
mpg = 0;
}
public Hybrid(String make, String model, double salesPrice, double salesTax, int mpg) {
super(make, model, salesPrice, salesTax);
this.mpg = mpg;
}
//A method that returns the base sales tax computed as 5% of the sales price
#Override
public double salesTax() {
if (mpg < 40)
discount = salesTax + 100;
else
discount = salesTax + 100 + (mpg * 2);
return discount;
}
//A toString method that returns a string containing the make and model of the
//automobile, the sales price, and the sales tax
#Override
public String toString() {
return make + model + salesPrice + discount + discount;
}
}
In my humble opinion, if understand correctly what you want to achieve, you have to create an instance of the "Hybrid" class in ProjectTwo's constructor, just like:
Declare the variable there you have all variable declarations, just to have it global:
private Hybrid hybr;
Create the instance in constructor:
hybr = new Hybrid("make", "hybrid's model", 20500.50, 12.5, 5);
And then in your code, there where you need to use to Hybrid's methods you call you method, in this case hybr.toString().

GUI Organization 5th BorderLayout

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.

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

moving data between classes with get and set

Ok, I am confused (and new to Java) about getters and setters. The code that I am working on will have multiple classes in a single container. The classes are UserInput, Totals, Greeting, and Checkboxes. The problem that I am having is that the UserInput panel accepts input from the user, and the data should be sent from the JTextFields to the complimentary fields in the Totals panel. I have been trying to use an action listener for the enter press, but to no avail.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.border.TitledBorder;
/**
*
* User input panel
* first panel
* has JTextFields for input of date for the hw/h, hours, and gallons
**/
public class UserInput extends JFrame
{
//variables/attributes
public double kwh;
public double hours;
public double gallons;
public double kFinal;
public double hFinal;
public double gFinal;
String i; //to hold the string from the textbox
//JFrame componants
private final JTextField kwhFieldU;
private final JTextField hoursFieldU;
private final JTextField gallonsFieldU;
private final JLabel kwhLabel;
private final JLabel hoursLabel;
private final JLabel gallonsLabel;
private final JPanel panel;
TextFieldHandler handler = new TextFieldHandler();
/**
*constructor
*/
public UserInput()
{
super("User Input");
// create the Grid
setLayout (new GridLayout (3,2));
//create the fields
kwhFieldU = new JTextField("Enter Kw/H", 15);
hoursFieldU = new JTextField("Enter Hours", 15);
gallonsFieldU = new JTextField("Enter Gallons", 15);
//create the labels
kwhLabel = new JLabel ("Kw/H");
hoursLabel = new JLabel ("Hours");
gallonsLabel = new JLabel ("Gallons");
//create the panel
panel = new JPanel();
kwhFieldU.addActionListener (handler);
hoursFieldU.addActionListener (handler);
gallonsFieldU.addActionListener (handler);
//Add a border
TitledBorder titled;
titled = BorderFactory.createTitledBorder("User Input");
//Add the tiles into the grid
add(kwhFieldU);
add(kwhLabel);
add(hoursFieldU);
add(hoursLabel);
add(gallonsFieldU);
add(gallonsLabel);
//Add panel to context frame
add(panel);
//display the window
setVisible(true);
}
//The get method to retrieve the user inputs
Scanner keyboard = new Scanner(System.in);
//get and set methods to store and retrieve date within the variables
//for kwh, hours, and gallons
/**
*
* #return
*/
/**
*
* #param k
*/
public void setKwh(double k)
{
kwh = k;
}
public double getKwh()
{
return kwh;
}
//get and set methods for hours
/**
*
* #param h
*/
public void setHours (double h)
{
hours = h;
}
public double getHours ()
{
return hours;
}
//get and set methods for gallons
/**
*
* #param g
*/
public void setGallons(double g)
{
gallons = g;
}
/**
*
* #return
*/
public double getGallons()
{
return gallons;
}
//Now add action listeners??? we will try it add the inner class to
//retrieve the variable data
/**
*
*/
private class TextFieldHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == kwhFieldU)
{
//relates string i with the action command
i = e.getActionCommand();
//turns string i into a double in variable kFinal
double kFinal = Double.parseDouble (i);
//relates kFinal with kwh
kwh = kFinal;
}
if (e.getSource() == hoursFieldU)
{
i = e.getActionCommand();
double hFinal = Double.parseDouble (i);
hours = hFinal;
}
if (e.getSource() == gallonsFieldU)
{
i = e.getActionCommand();
double gFinal = Double.parseDouble (i);
gallons = gFinal;
}
}
}
}
package applianceutilitycalculator;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
/**
*
* #author Gerber
*/
public class Totals extends JFrame
{
//constants for the grid layout mgr for the Total panel
private JPanel Panel;
private JLabel kwhLabel;
private JLabel hoursLabel;
private JLabel gallonsLabel;
private JLabel totalLabel;
public JTextField kwhFieldT;
public JTextField hoursFieldT;
public JTextField gallonsFieldT;
private JTextField totalFieldT;
public Totals()
{
super();
// create the Grid
setLayout (new GridLayout (4,2));
//Create the fields
kwhFieldT = new JTextField(15);
hoursFieldT = new JTextField(15);
gallonsFieldT = new JTextField(15);
totalFieldT = new JTextField(15);
//create the labels
kwhLabel = new JLabel ("Kw/H");
hoursLabel = new JLabel ("Hours");
gallonsLabel = new JLabel ("Gallons");
totalLabel = new JLabel ("Totals");
//Add a border
TitledBorder titled;
titled = BorderFactory.createTitledBorder("Totals");
//add panels to grid
add(kwhFieldT);
add(kwhLabel);
add(hoursFieldT);
add(hoursLabel);
add(gallonsFieldT);
add(gallonsLabel);
add(totalFieldT);
add(totalLabel);
//Add panel to context frame
add(Panel);
//display the window
setVisible(true);
}
//add actionperformed to get the return value to fill the text fields
//need to convert it from double into string ???
/**
*
* #param evt
*/
public void actionPerformed(ActionEvent evt)
{
kwhFieldT = kwh.getText();
hoursFieldT = hours.getText();
gallonsFieldT = gallons.getText();
}
}

Shade designer Program help having trouble with both approaches of this gui program

Shade Designer
A custom window shade designer charges a base fee of $50 per shade. In addition,
charges are added for certain styles, sizes, and colors as follows:
The object of this program with the description and the data below is to create an application that allows the user to select the style, size, color, and number of shades from list or combo boxes. The Total charges should be displayed.
Styles:
Regular shades: Add $0
Folding shades: Add $10
Roman shades: Add $15
Sizes:
25 inches wide: Add $0
27 inches wide: Add $2
32 inches wide: Add $4
40 inches wide: Add $6
Colors:
Natural: Add $5
Blue: Add $0
Teal: Add $0
Red: Add $0
Green: Add $0
I have taken two approaches and but the first program code below has a problem with the algorithim in which it doesn't add the additional cost of the styles, size and colors selection to computer the total price. I am not sure if it is a selection of each added such as total charges = styles selection + Size selection + colors selection. I am just not sure how to get this to compute and work with the correct algorithm in the code.
Code for shadedesigner.java below
The second code after this one is the second approach where a configpanel controls i beleive the list or combo box container and panels operations to the shadedesignerwindow.java. The config panel is suppose to work as a implementaton or interface for the shaddesignerwindow program. Below is what i have so far but i am not sure how to get the configpanel to work the way they want it with the shadedesignerwindow.
Below is my code that i have constructed for shadedesigner program. Everything works and complies yet I can't get the correct algorithm developed to add the additonal selections in to the total charges of the shade if a style, size and color is selected.
Repost correction 4/8/2012 edited code below.
* Filename: ShadeDesigner.java
* Programmer: Jamin A. Bishop
* Date: 3/31/2012
* #version 1.00 2012/4/2
*/
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class ShadeDesigner extends JFrame
{
private String[] styles = {"Regular Shades", "Folding Shades", "Roman Shades"};
private String[] size = {"25 Inches Wide", "27 Inches Wide",
"32 Inches Wide", "40 Inches Wide"};
private String[] colors = {"Natural", "Blue", "Teal",
"Red", "Green"};
private JLabel banner;// To display a banner
private JPanel bannerPanel;// To hold the banner
private JPanel stylesPanel;//
private JPanel sizePanel;//
private JPanel colorPanel;
private JPanel buttonPanel;//
private JList stylesList;
private JList sizeList;
private JList colorList;
private JTextField Styles;
private JTextField Size;
private JTextField Color;
private JButton calcButton;
private JButton ExitButton;
private double totalCharges = 50.00;
//Constants
private final int ROWS = 5;
private final double regularCost = 0.00;//base price for the blinds
private final double foldingCost = 10.00;//extra cost for folding blinds
private final double romanCost = 15.00;//extra cost for roman blinds
private final double twentyfiveInCost = 0.00; //extra cost for 25" blinds
private final double twentySevenInCost = 2.00;//extra cost for 27" blinds
private final double thirtyTwoInCost = 4.00;//extra cost for 32" blinds
private final double fourtyInCost = 6.00;//extra cost for 40" blinds
private final double naturalColorCost = 5.00;//extra cost for color
public ShadeDesigner()
{
//display a title
setTitle("Shade Designer");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create the banner on a panel and add it to the North region.
buildBannerPanel();
add(bannerPanel, BorderLayout.NORTH);
stylesPanel();
add(stylesPanel, BorderLayout.WEST);
sizePanel();
add(sizePanel, BorderLayout.CENTER);
colorPanel();
add(colorPanel, BorderLayout.EAST);
buttonPanel();
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
//build the bannerpanel
private void buildBannerPanel()
{
bannerPanel = new JPanel();
bannerPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
banner = new JLabel("Shade Designer");
banner.setFont(new Font("SanSerif", Font.BOLD, 24));
bannerPanel.add(banner);
}
//stylepanel
private void stylesPanel()
{
JLabel styleTitle = new JLabel("Select a Style.");
stylesPanel = new JPanel();
stylesPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
stylesList = new JList (styles);
stylesList.setVisibleRowCount(ROWS);
JScrollPane stylesScrollPane = new JScrollPane(stylesList);
stylesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
stylesList.addListSelectionListener(new stylesListListener());
stylesPanel.setLayout(new BorderLayout());
stylesPanel.add(styleTitle, BorderLayout.NORTH);
stylesPanel.add(stylesScrollPane, BorderLayout.CENTER);
Styles = new JTextField (5);
Styles.setEditable(false);
//stylesPanel.add(StylesLabel, BorderLayout.CENTER);
stylesPanel.add(Styles, BorderLayout.SOUTH);
}
private class stylesListListener implements ListSelectionListener
{
public void valueChanged (ListSelectionEvent e)
{
String selection = (String) stylesList.getSelectedValue();
Styles.setText(selection);
}
}
//size panel
private void sizePanel()
{
JLabel sizeTitle = new JLabel("Select a Size.");
sizePanel = new JPanel();
sizePanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
sizeList = new JList (size);
sizeList.setVisibleRowCount(ROWS);
JScrollPane stylesScrollPane = new JScrollPane(sizeList);
sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sizeList.addListSelectionListener(new sizeListListener());
sizePanel.setLayout(new BorderLayout());
sizePanel.add(sizeTitle, BorderLayout.NORTH);
sizePanel.add(stylesScrollPane, BorderLayout.CENTER);
//sizeLabel = new JLabel("Style Selected: ");
Size = new JTextField (5);
Size.setEditable(false);
//stylesPanel.add(StylesLabel, BorderLayout.CENTER);
sizePanel.add(Size, BorderLayout.SOUTH);
}
private class sizeListListener implements ListSelectionListener
{
public void valueChanged (ListSelectionEvent e)
{
String selection = (String) sizeList.getSelectedValue();
Size.setText(selection);
}
}
//color panel
private void colorPanel()
{
JLabel colorTitle = new JLabel("Select a Color.");
colorPanel = new JPanel();
colorPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
colorList = new JList (colors);
colorList.setVisibleRowCount(ROWS);
JScrollPane colorScrollPane = new JScrollPane(colorList);
colorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
colorList.addListSelectionListener(new colorListListener());
colorPanel.setLayout(new BorderLayout());
colorPanel.add(colorTitle, BorderLayout.NORTH);
colorPanel.add(colorScrollPane, BorderLayout.CENTER);
//sizeLabel = new JLabel("Style Selected: ");
Color = new JTextField (5);
Color.setEditable(false);
//stylesPanel.add(StylesLabel, BorderLayout.CENTER);
colorPanel.add(Color, BorderLayout.SOUTH);
}
private class colorListListener implements ListSelectionListener
{
public void valueChanged (ListSelectionEvent e)
{
String selection = (String) colorList.getSelectedValue();
Color.setText(selection);
}
}
//button panel
private void buttonPanel()
{
calcButton= new JButton ("Calculate Charges");
calcButton.addActionListener(new calcButtonListener());
ExitButton = new JButton ("Exit");
ExitButton.addActionListener(new ExitButtonListener());
buttonPanel = new JPanel();
buttonPanel.add(calcButton);
buttonPanel.add(ExitButton);
}
private class calcButtonListener implements ActionListener
{
//actionPerformed method parementer e an actionevent object
public void actionPerformed(ActionEvent e)
{
// Create a DecimalFormat object.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Display the total.
JOptionPane.showMessageDialog(null, "TotalCharges: $" +
dollar.format(totalCharges));
}
}
private class ExitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//Exit the applicaiton
System.exit(0);
}
}
//static void main for the string
public static void main(String[] args)
{
new ShadeDesigner();
}
}
* File Name: ConfigPanel.java
* Date: 3/26/2012
* Programmer: Jamin A. Bishop
* #version 1.00 2012/3/22
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
class ConfigPanel extends JPanel
{
private JLabel SelectStyleLabel;
private JLabel SelectSizeLabel;
private JLabel SelectColorLabel;
private JPanel StylePricePanel;
private JPanel SizePricePanel;
private JPanel ColorPricePanel;
private JComboBox SelectStyleBox;
private JComboBox SelectSizeBox;
private JComboBox SelectColorBox;
private final int ROWS = 5;
private final int RegShadeadd = 0.00;
private final int FoldShadeadd = 10.00;
private final int RomanShadeadd = 15.00;
private final int 25inchadd = 0.00;
private final int 27inchadd = 2.00;
private final int 32inchadd = 4.00;
private final int 40inchadd = 6.00;
private final int Naturaladd = 5.00;
private final int Blueadd = 0.00;
private final int Tealadd = 0.00;
private final int Redadd = 0.00;
private final int Greenadd = 0.00;
//create the arrays to hold the values of the combo box's
private String[] StylePrice = {"Regular Shades", "Folding Shades", "Roman Shades"};
private String[] SizePrice = {"25 inches Wide", "27 inches Wide", "32 inches Wide", "40 inches Wide"};
private String[] ColorPrice = {"Nature", "Blue", "Teal", "Red", "Green"};
// constructor
public ConfigPanel ()
{
//build the panel
buildStylePricePanel();
buildSizePricePanel();
buildColorPricePanel();
//add the panel to the content pane
add(StylePricePanel, BorderLayout.WEST);
add(SizePricePanel, BorderLayout.CENTER);
add(ColorPricePanel, BorderLayout.EAST);
}
//methods to hold the strings
public double getStylePrice ()
{
String selection = (String) StylePrice.getName(StylePrice);
StylePrice.setText(selection);
}
public double getSizePrice ()
{
}
public double getColorPrice ()
}
}
the confgpanel is suppose to work with this code below
* Filename: ShadeDesignerWindow.java
* Programmer: Jamin A. Bishop
* Date: 3/31/2012
* #version 1.00 2012/3/31
*/
public class ShadeDesignerWindow extends JFrame
{
private JLabel banner; // To display a banner
private ConfigPanel configPanel; // To offer various configurations
private JPanel bannerPanel; // To hold the banner
private JPanel buttonPanel; // To hold the buttons
private JButton calcButton; // To calculate total charges
private JButton exitButton; // To exit the application
//constructor
public ShadeDesignerWindow()
{
//Title Display
super("Shade Designer");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create the banner on a panel.
bannerPanel = new JPanel();
bannerPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
banner = new JLabel("Shade Designer");
banner.setFont(new Font("SanSerif", Font.BOLD, 24));
bannerPanel.add(banner);
// Create a configuration panel.
configPanel = new ConfigPanel();
// Build the button panel.
buildButtonPanel();
// Add the banner and other panels to the content pane.
add(bannerPanel, BorderLayout.NORTH);
add(configPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
// Pack and display the window.
pack();
setVisible(true);
}
//buildButtonPanel method
private void buildButtonPanel()
{
// Create a button to calculate the charges.
calcButton = new JButton("Calculate Charges");
// Add an action listener to the button.
calcButton.addActionListener(new CalcButtonListener());
// Create a button to exit the application.
exitButton = new JButton("Exit");
// Add an action listener to the button.
exitButton.addActionListener(new ExitButtonListener());
// Put the buttons in their own panel.
buttonPanel = new JPanel();
buttonPanel.add(calcButton);
buttonPanel.add(exitButton);
}
//calcButtonListner and calcbutton component
private class CalcButtonListener implements ActionListener
{
//actionPerformed method
public void actionPerformed(ActionEvent e)
{
double totalCharges = 50.0; // Total charges
// Create a DecimalFormat object to format output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Get the total charges
totalCharges += configPanel.getStylePrice() + configPanel.getSizePrice() +
configPanel.getColorPrice();
// Display the message.
JOptionPane.showMessageDialog(null, "Total Charges: $" +
dollar.format(totalCharges));
}
} // End of inner class
//ExitButtonListener and exitButton component
private class ExitButtonListener implements ActionListener
{
//actionPerformed method
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
} // End of inner class
//The main method instantiates the ShadeDesigner class
public static void main(String[] args)
{
ShadeDesignerWindow sdw = new ShadeDesignerWindow();
}
}
I need help trying to get either code above to work. I do not get the whole configpanel approach or what it is suppose to do. I started with the one file program because that is the way i learned java programming. Even with implemetation it was always one swing file or gui not two.
Thank you for your help.
Jamin A. Bishop
Just as ConfigPanel was factored out of the original program, pull out styles, sizes and colors as separate classes, each managing its own names and amounts. Let each of these implement a suitable interface:
interface MarginalBillable {
double getMarginalCostOfCurrentSelection();
}
Then ConfigPanel can have just one method that returns the total of all current selections. For extra credit, make the parent of the three panels abstract.
class ConfigPanel {
StylePanel stylePanel = new StylePanel();
SizePanel sizePanel = new SizePanel();
ColorPanel colorPanel = new ColorPanel();
double getTotalMarginalAmount() {
return stylePanel.getMarginalCostOfCurrentSelection()
+ sizePanel.getMarginalCostOfCurrentSelection()
+ colorPanel.getMarginalCostOfCurrentSelection();
}
}
interface MarginalBillable {
double getMarginalCostOfCurrentSelection();
}
class StylePanel extends JPanel implements MarginalBillable {
double value;
#Override
public double getMarginalCostOfCurrentSelection() {
return value; //based on current settings
}
}
class SizePanel extends JPanel implements MarginalBillable {
double value;
#Override
public double getMarginalCostOfCurrentSelection() {
return value; //based on current settings
}
}
class ColorPanel extends JPanel implements MarginalBillable {
double value;
#Override
public double getMarginalCostOfCurrentSelection() {
return value; //based on current settings
}
}

Categories

Resources