So my program is designed to take in 2 values, make a calculation, and give this calculations value. I want to display it as a prompt in the GUI in the actionPerformed section after the button is clicked. It looks like it should show up but I can't seem to find why it isn't? It's "prompt2" that isn't showing up. Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Windchill extends JFrame implements ActionListener{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private String degree;
private String wind;
private int degreeInt;
private int windInt;
private double windChillInt;
private JButton windButton;
private JLabel prompt;
private JLabel prompt1;
private JLabel prompt2;
private JTextField inputLine;
private JTextField inputLine1;
public Windchill(){
setTitle("Windchill");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
inputLine = new JTextField();
inputLine.setColumns(3);
inputLine.addActionListener(this);
contentPane.add(inputLine);
prompt = new JLabel();
prompt.setText("Enter the degrees in Farienheight ");
prompt.setSize(150,25);
contentPane.add(prompt);
inputLine1 = new JTextField();
inputLine1.setColumns(3);
inputLine1.addActionListener(this);
contentPane.add(inputLine1);
prompt1 = new JLabel();
prompt1.setText("Enter the wind speed in MPH");
prompt1.setSize(150,25);
contentPane.add(prompt1);
windButton = new JButton("Calculate windchill");
contentPane.add(windButton);
windButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() instanceof JButton){
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == windButton){
degree = inputLine.getText();
degreeInt = Integer.parseInt(degree);
wind = inputLine1.getText();
windInt = Integer.parseInt(wind);
windChillInt = 0.08 * (degreeInt - 91.4)*(3.71* (Math.sqrt(windInt)) + 5.81 - 0.25 *windInt) + 91.4;
prompt2 = new JLabel();
prompt2.setText("The windchill is " + windChillInt);
prompt2.setSize(150,25);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(prompt2);
}
}
}
public static void main(String[] args) {
Windchill frame;
frame = new Windchill();
frame.setVisible(true);
}
}
prompt2 isn't showing up as Swing containers need to be validated for any newly added components can be visible. Also it's good practice to repaint. You could do:
contentPane.revalidate();
contentPane.repaint();
Side Notes:
It is unnecessary to set the layout again for the your ActionListener
contentPane.add(prompt2) can be simplified to add(prompt2)
Alternatively, you could just add the prompt2 JLabel to the contentPane on startup with empty String content and call setText to update.
Related
Trying to make flashcard application. The JButton b_switchmode will be used to switch between panels (an edit mode and a test mode, both have panels created for separate use). Not quite sure how to go from the GUI I've created. Ideally I would click the JButton b_switchmode and I would be able to switch from "Edit Mode" to "Test Mode".
I'm aware that a CardLayout may be needed but I'm unable to implement the correct syntax to make the program executable.
So I want to know how to:
insert CardLayout to be able to switch between JPanels
allow JButton b_switchmode to execute the switch between JPanels
public class App2 {
private static JFrame frame;
private static JPanel editpanel;
private static JPanel testpanel;
private static JLabel l_appmode;
private static JLabel l_number;
private static JLabel l_question;
private static JLabel l_answer;
public static JTextField t_questions;
public static JTextField t_answer;
public static JButton b_switchmode;
public static JButton b_previous;
public static JButton b_next;
public static JButton b_add;
public static JButton b_save;
public static JButton b_question;
public static JButton b_answer;
static int width = 600;
static int height = 450;
public static void main(String[] args) {
// TODO Auto-generated method stub
gui();
}
private static void gui(){
frame = new JFrame("Assignment2");
frame.setTitle("Flash Cards");
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l_appmode = new JLabel("Current Mode: Edit");
l_number = new JLabel ("");
l_question = new JLabel("Question:");
l_answer = new JLabel("Answer:");
t_questions = new JTextField("");
t_answer = new JTextField("");
b_switchmode = new JButton("Switch Mode");
b_previous = new JButton("Previous");
b_next = new JButton("Next");
b_add = new JButton("Add");
b_save = new JButton("Save");
b_question = new JButton("Question");
b_answer = new JButton("Answer");
editpanel = new JPanel();
int rows = 6, columns = 1;
int hgap = 20; int vgap = 20;
editpanel.setLayout(new GridLayout(rows, columns, hgap,
vgap));
editpanel.add(l_appmode);
editpanel.add(l_number);
editpanel.add(l_question);
editpanel.add(t_questions);
editpanel.add(l_answer);
editpanel.add(t_answer);
editpanel.add(b_switchmode);
editpanel.add(b_previous);
editpanel.add(b_next);
editpanel.add(b_add);
editpanel.add(b_save);
//testpanel.add(b_question);
//testpanel.add(t_questions);
//testpanel.add(b_answer);
//testpanel.add(t_answer);
frame.add(editpanel);
//frame.add(testpanel);
frame.setVisible(true);
}
I am having some issues getting my GUI to exit on close. I have tried
frame.setDefaultCloseOperation(JFrame.CLOSE_ON_EXIT);
I have tried it with DISPOSE_ON_EXIT and it is not working.
when I run the program without any of that code and I click "X" it closes the window, but it is still running.
When I put that code in it will not compile and I get this error.
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
at InvestmentFrame2.main(InvestmentFrame2.java:103)
I have tried reading suggestions on here as well as on other websites. The book I am using to learn this stuff didn't really explain anything about it, but just had it in some example code So I have just been trying some various suggestions.
I couldn't figure out if I maybe needed to import something else or if there is some other issue?
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.JPanel;
import javax.swing.JTextField;
public class InvestmentFrame2 extends JFrame
{
private static final int FRAME_WIDTH = 450;
private static final int FRAME_HEIGHT = 250;
private static final double DEFAULT_RATE = 0;
private static final double INITIAL_BALANCE = 0;
private static final double YEARS = 0;
private JLabel rateLabel;
private JLabel balanceLabel;
private JLabel yearsLabel;
private JTextField rateField;
private JTextField balanceField;
private JTextField yearsField;
private JButton button;
private JLabel resultLabel;
private double balance;
public InvestmentFrame2()
{
balance = INITIAL_BALANCE;
resultLabel = new JLabel("Balance: " + balance);
createTextField();
createButton();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createTextField()
{
rateLabel = new JLabel("Interest Rate: ");
balanceLabel = new JLabel("Account Balance: ");
yearsLabel = new JLabel("Number of Years Saving: ");
final int FIELD_WIDTH = 10;
rateField = new JTextField(FIELD_WIDTH);
rateField.setText ("" + DEFAULT_RATE);
balanceField = new JTextField(FIELD_WIDTH);
balanceField.setText("" + INITIAL_BALANCE);
yearsField = new JTextField(FIELD_WIDTH);
yearsField.setText("" + YEARS);
}
class AddInterestListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double rate = Double.parseDouble(rateField.getText());
double accountBalance = Double.parseDouble(balanceField.getText());
double years = Double.parseDouble(yearsField.getText());
double interest = (accountBalance * rate / 100) * years;
balance = accountBalance + interest;
resultLabel.setText("Balance: " + balance);
}
}
private void createButton()
{
button = new JButton("Calculate Balance");
ActionListener listener = new AddInterestListener();
button.addActionListener(listener);
}
private void createPanel()
{
JPanel panel = new JPanel();
panel.add(rateLabel);
panel.add(rateField);
panel.add(balanceLabel);
panel.add(balanceField);
panel.add(yearsLabel);
panel.add(yearsField);
panel.add(button);
panel.add(resultLabel);
add(panel);
}
public static void main(String[] args)
{
JFrame frame = new InvestmentFrame2();
frame.setTitle("Savings Frame");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_EXIT);
frame.setVisible(true);
}
}
You're trying to run a class which is uncompilable...JFrame.DISPOSE_ON_EXIT doesn't exist. You are actually looking for JFrame.EXIT_ON_CLOSE
Take a minute to read the JavaDocs for JFrame
public void setDefaultCloseOperation(int operation) Sets the
operation that will happen by default when the user initiates a
"close" on this frame. You must specify one of the following
choices: * DO_NOTHING_ON_CLOSE (defined in WindowConstants):
Don't do anything; require the program to handle the operation in the
windowClosing method of a registered WindowListener object. *
HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the
frame after invoking any registered WindowListener objects. *
DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and
dispose the frame after invoking any registered WindowListener
objects. * EXIT_ON_CLOSE (defined in JFrame): Exit the
application using the System exit method. Use this only in
applications. The value is set to HIDE_ON_CLOSE by default.
Changes to the value of this property cause the firing of a property
change event, with property name "defaultCloseOperation".
You might also find How to Make Frames (Main Windows) of some use...
You should also ensure that your UI is created within the context of the Event Dispatching Thread, take a look at Initial Threads for more details
Updated with example
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.JPanel;
import javax.swing.JTextField;
public class InvestmentFrame2 extends JFrame {
private static final int FRAME_WIDTH = 450;
private static final int FRAME_HEIGHT = 250;
private static final double DEFAULT_RATE = 0;
private static final double INITIAL_BALANCE = 0;
private static final double YEARS = 0;
private JLabel rateLabel;
private JLabel balanceLabel;
private JLabel yearsLabel;
private JTextField rateField;
private JTextField balanceField;
private JTextField yearsField;
private JButton button;
private JLabel resultLabel;
private double balance;
public InvestmentFrame2() {
balance = INITIAL_BALANCE;
resultLabel = new JLabel("Balance: " + balance);
createTextField();
createButton();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createTextField() {
rateLabel = new JLabel("Interest Rate: ");
balanceLabel = new JLabel("Account Balance: ");
yearsLabel = new JLabel("Number of Years Saving: ");
final int FIELD_WIDTH = 10;
rateField = new JTextField(FIELD_WIDTH);
rateField.setText("" + DEFAULT_RATE);
balanceField = new JTextField(FIELD_WIDTH);
balanceField.setText("" + INITIAL_BALANCE);
yearsField = new JTextField(FIELD_WIDTH);
yearsField.setText("" + YEARS);
}
class AddInterestListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double rate = Double.parseDouble(rateField.getText());
double accountBalance = Double.parseDouble(balanceField.getText());
double years = Double.parseDouble(yearsField.getText());
double interest = (accountBalance * rate / 100) * years;
balance = accountBalance + interest;
resultLabel.setText("Balance: " + balance);
}
}
private void createButton() {
button = new JButton("Calculate Balance");
ActionListener listener = new AddInterestListener();
button.addActionListener(listener);
}
private void createPanel() {
JPanel panel = new JPanel();
panel.add(rateLabel);
panel.add(rateField);
panel.add(balanceLabel);
panel.add(balanceField);
panel.add(yearsLabel);
panel.add(yearsField);
panel.add(button);
panel.add(resultLabel);
add(panel);
}
public static void main(String[] args) {
JFrame frame = new InvestmentFrame2();
frame.setTitle("Savings Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Compiles and runs just fine for me...
I've only been working with Java for about a year now and have just gotten into the basics of GUI. I'm writing a program that will calculate the center of mass between 2, 3, 4, or 5 points (user's option). Depending on the number of points the user wants to enter, a number of editable JTextFields appear to get input for coordinates and masses of those coordinates. Unfortunately, when asked to calculate the center of mass, the button won't display what I want. The way it's written now is the only way I've gotten it to compile/run without an empty string error. I believe it has to do with how I've initialized the variables/where they're initialized between constructors, but I can't for the life of me figure out where that problem lies exactly. Any help will be greatly appreciated! I've attached the code - I know it's long, but you never know what can be useful. Thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class ComboBox extends JFrame
/*************VARIABLES*******************************************************/
{
private final int WIDTH = 1500;
private final int HEIGHT = 1500;
private JPanel northPanel;
private JPanel centerPanel;
private JPanel blankPanel;
private JPanel pointsPanel;
private JPanel selectedPointsPanel;
private JComboBox pointsBox;
private JTextField selectedPoints;
private JLabel selection;
private String choose = "Choose an option...";
private String twoPoints = "2 points";
private String threePoints = "3 points";
private String fourPoints = "4 points";
private String fivePoints = "5 points";
private String[] points = {choose, twoPoints, threePoints, fourPoints, fivePoints};
private JPanel coordinatesPanel;
private JPanel cPanel;
private JTextField xField1;
private JTextField xField2;
private JTextField xField3;
private JTextField xField4;
private JTextField xField5;
private JTextField yField1;
private JTextField yField2;
private JTextField yField3;
private JTextField yField4;
private JTextField yField5;
private JLabel instructions;
private JLabel X;
private JLabel Y;
private JLabel blankLabel;
private JPanel massPanel;
private JTextField mass1 = new JTextField(10);
private JTextField mass2 = new JTextField(10);
private JTextField mass3 = new JTextField(10);
private JTextField mass4 = new JTextField(10);
private JTextField mass5 = new JTextField(10);
private JLabel instructions2;
Boolean calcBool = false;
private JButton calcButton = new JButton("Calculate");
private JButton resetButton = new JButton("Reset");
private JPanel displayPanel;
private double centerX;
private double centerY;
private JLabel display;
private double x1, x2, x3, x4, x5;
private double y1, y2, y3, y4, y5;
private double m1, m2, m3, m4, m5;
/**********************************WINDOW************************************/
public ComboBox()
{
super("Choose an option");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3,2));
setLocationRelativeTo(null);
setResizable(true);
setSize(WIDTH, HEIGHT);
buildPointsPanel();
buildCoordinatesPanel();
buildMassPanel();
buildDisplayPanel();
buildBlankPanel();
add(pointsPanel);
add(coordinatesPanel);
add(massPanel);
add(blankPanel);
add(calcButton);
add(blankPanel);
add(resetButton);
add(blankPanel);
add(displayPanel);
calcButton.addActionListener(new CalcButtonListener());
pointsBox.addActionListener(new ComboBoxListener());
//resetButton.addActionListener(new ResetButtonListener());
pack();
setVisible(true);
}
/************************BUILD ALL THE PANELS**********************/
private void buildBlankPanel()
{
blankPanel = new JPanel();
}
private void buildPointsPanel()
{
pointsPanel = new JPanel();
pointsPanel.setLayout(new GridLayout(3,1));
pointsBox = new JComboBox(points);
pointsBox.addActionListener(new ComboBoxListener());
pointsPanel.add(pointsBox);
selection = new JLabel("You selected: ");
selectedPoints = new JTextField(10);
selectedPoints.setEditable(false);
pointsPanel.add(selection);
pointsPanel.add(selectedPoints);
}
private void buildCoordinatesPanel()
{
coordinatesPanel = new JPanel();
coordinatesPanel.setLayout(new GridLayout(6,2));
instructions = new JLabel("Please enter the X and Y values of your points below.");
JLabel blank = new JLabel("");
X = new JLabel("X values");
Y = new JLabel("Y values");
blankLabel = new JLabel("");
coordinatesPanel.add(instructions);
coordinatesPanel.add(blankLabel);
coordinatesPanel.add(X);
coordinatesPanel.add(Y);
xField1 = new JTextField(10);
xField1.setEditable(true);
yField1 = new JTextField(10);
yField1.setEditable(true);
xField2 = new JTextField(10);
xField2.setEditable(true);
yField2 = new JTextField(10);
yField2.setEditable(true);
xField3 = new JTextField(10);
xField3.setEditable(true);
yField3 = new JTextField(10);
yField3.setEditable(true);
xField4 = new JTextField(10);
xField4.setEditable(true);
yField4 = new JTextField(10);
yField4.setEditable(true);
xField5 = new JTextField(10);
xField5.setEditable(true);
yField5 = new JTextField(10);
yField5.setEditable(true);
}
private void buildMassPanel()
{
massPanel = new JPanel();
instructions2 = new JLabel("Please enter the masses of your points");
massPanel.add(instructions2);
mass1.setEditable(true);
mass2.setEditable(true);
mass3.setEditable(true);
mass4.setEditable(true);
mass5.setEditable(true);
}
private void buildDisplayPanel()
{
displayPanel = new JPanel();
//display = new JLabel("The center of mass is located at (" + centerX + "," + centerY
+").");
//displayPanel.add(display);
}
/********************************COMBOBOX LISTENER****************************/
private class ComboBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{ //The following asks the user to select the number of points they want and stores
it
String select =(String) pointsBox.getSelectedItem();
selectedPoints.setText(select);
//The following determines how many text fields to display depending on how many
points the user wants
if (select==twoPoints)
{
coordinatesPanel.add(xField1);
coordinatesPanel.add(yField1);
coordinatesPanel.add(xField2);
coordinatesPanel.add(yField2);
massPanel.add(mass1);
massPanel.add(mass2);
centerX = ((m1*x1)+(m2*x2)/(m1+m2));
centerY = ((m1*y1)+(m2*y2)/(m1+m2));
}
if (select==threePoints)
{
coordinatesPanel.add(xField1);
coordinatesPanel.add(yField1);
coordinatesPanel.add(xField2);
coordinatesPanel.add(yField2);
coordinatesPanel.add(xField3);
coordinatesPanel.add(yField3);
massPanel.add(mass1);
massPanel.add(mass2);
massPanel.add(mass3);
centerX = ((m1*x1)+(m2*x2)+(m3*x3)/(m1+m2+m3));
centerY = ((m1*y1)+(m2*y2)+(m3*y3)/(m1+m2+m3));
}
if (select==fourPoints)
{
coordinatesPanel.add(xField1);
coordinatesPanel.add(yField1);
coordinatesPanel.add(xField2);
coordinatesPanel.add(yField2);
coordinatesPanel.add(xField3);
coordinatesPanel.add(yField3);
coordinatesPanel.add(xField4);
coordinatesPanel.add(yField4);
massPanel.add(mass1);
massPanel.add(mass2);
massPanel.add(mass3);
massPanel.add(mass4);
centerX = ((m1*x1)+(m2*x2)+(m3*x3)+(m4*x4)/(m1+m2+m3+m4));
centerY = ((m1*y1)+(m2*y2)+(m3*y3)+(m4*y4)/(m1+m2+m3+m4));
}
if (select==fivePoints)
{
coordinatesPanel.add(xField1);
coordinatesPanel.add(yField1);
coordinatesPanel.add(xField2);
coordinatesPanel.add(yField2);
coordinatesPanel.add(xField3);
coordinatesPanel.add(yField3);
coordinatesPanel.add(xField4);
coordinatesPanel.add(yField4);
coordinatesPanel.add(xField5);
coordinatesPanel.add(yField5);
massPanel.add(mass1);
massPanel.add(mass2);
massPanel.add(mass3);
massPanel.add(mass4);
massPanel.add(mass5);
centerX = ((m1*x1)+(m2*x2)+(m3*x3)+(m4*x4)+(m5*x5)/(m1+m2+m3+m4+m5));
centerY = ((m1*y1)+(m2*y2)+(m3*y3)+(m4*y4)+(m5*y5)/(m1+m2+m3+m4+m5));
}
if (select==choose)
{
JOptionPane.showMessageDialog(null, "Please select a valid option");
}
}
}
/********************************CALC BUTTON LISTENER******************************/
private class CalcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
display = new JLabel("The center of mass is located at (" + centerX + "," + centerY
+").");
displayPanel.add(display);
}
}
/******************************MAIN METHOD***************************/
public static void main(String[] args)
{
new ComboBox();
}
What you should do is instantiate the display, where you have it declared.
JLabel display = new JLabel(" ");
Then add it to the GUI, wherever in the code you're adding all the other components. Than in your listener class, just set the text
public void actionPerformed(ActionEvent e){
display.setText("some text");
}
The way you're doing it might mess up your desired GUI formatting. If you were to do it though, you need to revalidate() and repaint() after adding any new components. I'd recommend using the former.
Don't know where is your specific problem, but looking at your code i see some potential bugs. In java you compare objects equality with equals() not with == .== is just for references.
So changes all lines where you compare Strings with == replace with equals.
For example change
select==fivePoints
to
select.equals(fivePoints)
Having attributes like
private JTextField mass1 = new JTextField(10);
private JTextField mass2 = new JTextField(10);
private JTextField mass3 = new JTextField(10);
private JTextField mass4 = new JTextField(10);
private JTextField mass5 = new JTextField(10);
is not the best way, you can store them in a Collection or in array.
private List<JTextField> masses;
Always when you add a component call revalidate and repaint.
display = new JLabel("The center of mass is located at (" + centerX + "," + centerY
+").");
displayPanel.add(display);
displayPanel.revalidate();
displayPanel.repaint();
I have been attempting to recreate this in Java: http://imgur.com/pjt7SMZ
This is the code I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Display extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 350;
private static final int FRAME_X_ORIGIN = 100;
private static final int FRAME_Y_ORIGIN = 75;
private JButton readFileButton;
private JButton exitButton;
private JButton statsButton;
private JButton clearButton;
private JButton helpButton;
private JLabel headerLabel;
public Display() {
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle("CSCE155A Course Offering Viewer");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel header = new JPanel(new GridLayout(1, 1, 5, 5));
headerLabel = new JLabel("CSCE155A Course Offering Viewer");
header.add(headerLabel);
}
public static void main(String[] args) {
Display frame = new Display();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
}
}
My problem is with JPanel. As we were instructed, we are suppose to use the BorderLayout with GridLayout inside, but nothing happens whenever I run the code. Is JPanel even the best way to do this? Right now I'm just trying to get the header to work.
According to your design, you should not add JLabel on JPanel. Add headerLabel on top of JFrame and align the text CENTER.
headerLabel = new JLabel("CSCE155A Course Offering Viewer",JLabel.CENTER);
add(headerLabel,BorderLayout.NORTH);// Add it with JFrame.
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
}
}