Remove Java Panels without crashing your program - java

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

Related

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

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

formatting JTextfields using another class

this is the code of the Gui Design class and below is the Class that provides functionality to the program. Im trying to get user input from the textfields so i can remove the text using the clearAll method and also save user input using the saveit method.I tried using nameEntry.setText(""); in the clearAll method but it wont work can someone help me please!
//Import Statements
import javax.swing.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Customer extends JFrame {
Function fun = new Function();
public static void main(String[]args){
Customer.setLookAndFeel();
Customer cust = new Customer();
}
public Customer(){
super("Resident Details");
setSize(500,500);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout two = new FlowLayout(FlowLayout.LEFT);
setLayout(two);
JPanel row1 = new JPanel();
JLabel name = new JLabel("First Name",JLabel.LEFT);
JTextField nameEntry = new JTextField("",20);
row1.add(name);
row1.add(nameEntry);
add(row1);
JPanel row2 = new JPanel();
JLabel surname = new JLabel("Surname ",JLabel.LEFT);
JTextField surnameEntry = new JTextField("",20);
row2.add(surname);
row2.add(surnameEntry);
add(row2);
JPanel row3 = new JPanel();
JLabel contact1 = new JLabel("Contact Details : Email ",JLabel.LEFT);
JTextField contact1Entry = new JTextField("",10);
FlowLayout newflow = new FlowLayout(FlowLayout.LEFT,10,30);
setLayout(newflow);
row3.add(contact1);
row3.add(contact1Entry);
add(row3);
JPanel row4 = new JPanel();
JLabel contact2 = new JLabel("Contact Details : Phone Number",JLabel.LEFT);
JTextField contact2Entry = new JTextField("",10);
row4.add(contact2);
row4.add(contact2Entry);
add(row4);
JPanel row5 = new JPanel();
JLabel time = new JLabel("Duration Of Stay ",JLabel.LEFT);
JTextField timeEntry = new JTextField("",10);
row5.add(time);
row5.add(timeEntry);
add(row5);
JPanel row6 = new JPanel();
JComboBox<String> type = new JComboBox<String>();
type.addItem("Type Of Room");
type.addItem("Single Room");
type.addItem("Double Room");
type.addItem("VIP Room");
row6.add(type);
add(row6);
JPanel row7 = new JPanel();
FlowLayout amt = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(amt);
JLabel amount = new JLabel("Amount Per Day ");
JTextField AmountField = new JTextField("\u20ac ",10);
row7.add(amount);
row7.add(AmountField);
add(row7);
JPanel row8 = new JPanel();
FlowLayout prc = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(prc);
JLabel price = new JLabel("Total Price ");
JTextField priceField = new JTextField("\u20ac ",10);
row8.add(price);
row8.add(priceField);
add(row8);
JPanel row9 = new JPanel();
JButton clear = new JButton("Clear");
row9.add(clear);
add(row9);
JPanel row10 = new JPanel();
JButton save = new JButton("Save");
save.addActionListener(fun);
row10.add(save);
add(row10);
//Adding ActionListners
nameEntry.addActionListener(fun);
clear.addActionListener(fun);
save.addActionListener(fun);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
}
//Import Statements
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Function implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Add Customer")) {
Login();
}
else if(command.equals("Register")){
Registration();
}
else if(command.equals("Exit")){
System.exit(0);
}
else if(command.equals("Clear")){
ClearAllFields();
}
else if(command.equals("Save")){
SaveIt();
}
}
public static void Login(){
Customer cust = new Customer();
}
public static void Registration(){
//Do Nothing
}
//This clears all the text from the JTextFields
public static void ClearAllFields(){
}
//This will save Info on to another Class
public static void SaveIt(){
}
}
Alternatively, you can make nameEntry known to the Function class by defining it before calling the constructor for Function and then passing it into the constructor, like:
JTextField nameEntry = new JTextField("",20);
Function fun = new Function(nameEntry);
Then, in Function, add nameEntry as a member variable of Function and make a constructor for Function which accepts nameEntry, (right after the "public class Function..." line), like:
JTextField nameEntry;
public Function(JTextField nameEntry) {
this.nameEntry = nameEntry;
}
Now, the following will compile:
public void ClearAllFields(){
nameEntry.setText("");
}
And, the Clear button will clear the name field.
Again as per comments, one simple way to solve this is to give the gui public methods that the controller (the listener) can call, and then pass the current displayed instance of the GUI into the listener, allowing it to call any public methods that the GUI might have. The code below is simpler than yours, having just one JTextField, but it serves to illustrate the point:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class GUI extends JPanel {
private JTextField textField = new JTextField(10);
private JButton clearButton = new JButton("Clear");
public GUI() {
// pass **this** into the listener class
MyListener myListener = new MyListener(this);
clearButton.addActionListener(myListener);
clearButton.setMnemonic(KeyEvent.VK_C);
add(textField);
add(clearButton);
}
// public method in GUI that will do the dirty work
public void clearAll() {
textField.setText("");
}
// other public methods here to get text from the JTextFields
// to set text, and do whatever else needs to be done
private static void createAndShowGui() {
GUI mainPanel = new GUI();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyListener implements ActionListener {
private GUI gui;
// use constructor parameter to set a field
public MyListener(GUI gui) {
this.gui = gui;
}
#Override
public void actionPerformed(ActionEvent e) {
gui.clearAll(); // call public method in field
}
}
A better and more robust solution is to structure your program in a Model-View-Controller fashion (look this up), but this would probably be overkill for this simple academic exercise that you're doing.

trouble with creating JTable to display data [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am doing this payroll project for school.
The idea is for the user to input the employee's name, work hour, hourly rate, and select department from the ComboBox.
There will display 3 buttons, "Add More", "Display Result", and "exit".
"Add More" button will store the input into several arryalist and set the textfield to blank to allow more input.
"Display Result" will generate a JTable at the bottom JPanel to display the employee's name, department, and weekly salary.
I am running into the problem of nothing shows up after hitting the "Display Result" button. Maybe I have misunderstand the purpose of the button event, but I am really confused right now. Please help!
Here is a photobucket directURL PrtSc of the UI, hope it helps.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class PayrollFrame extends JFrame
{
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame()
{
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLayout(new GridLayout(3,1));
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel);
add(buttonPanel);
add(outputPanel);
setVisible(true);
}
private void buildInputPanel()
{
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel()
{
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel()
{
outputPanel = new JPanel();
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][2]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="Add More")
{
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
}
else if(e.getActionCommand()=="Display Result")
{
printData();
}
else if(e.getActionCommand()=="Exit")
{
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString)
{
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if(tempHour<=40)
{
salary.add(Double.toString(tempHour * tempRate));
}
else
{
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
Let's start with...
if (e.getActionCommand() == "Add More") {
Is not how you compare Strings in Java, you need to use the equals method instead, something like...
if ("Add More".equals(e.getActionCommand())) {
for example
Next you do...
add(inputPanel);
add(buttonPanel);
add(outputPanel);
which, when using a BorderLayout, adds each of the components to the default position within the BorderLayout, you need to provide position constraints for each component, otherwise strange things begin to happen, for example...
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
add(outputPanel, BorderLayout.SOUTH);
I just realised that you're using a GridLayout, personally, I think you'll get a better result from BorderLayout, but that's me
And then you create a new instance of resultTable and outputPanel, but you never add outputPanel to anything...
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][1]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
A better idea would be to create resultTable, wrap in a JScrollPane and add it to your screen.
When you want to "print" the data, create a new TableModel and apply it to the JTable
For example...
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
Take a look at How to Use Tables and How to Use Scroll Panes for more details
Example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class PayrollFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
PayrollFrame frame = new PayrollFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame() {
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel);
add(outputPanel, BorderLayout.SOUTH);
setVisible(true);
}
private void buildInputPanel() {
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel() {
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
TableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if ("Add More".equals(e.getActionCommand())) {
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
} else if ("Display Result".equals(e.getActionCommand())) {
printData();
} else if ("Exit".equals(e.getActionCommand())) {
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString) {
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if (tempHour <= 40) {
salary.add(Double.toString(tempHour * tempRate));
} else {
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}
Thanks for #MadProgrammer 's help! His reply helps me to fix many problems I have, and really tried to explain things to me. After consulting with my instructor, I have successfully compile and run my program by editing the printData method.
private void printData()
{
DefaultTableModel model = new DefaultTableModel(columnNames,name.size());
resultTable.setModel(model);
for(int i=0; i<name.size(); i++)
{
resultTable.setValueAt(name.get(i),i,0);
resultTable.setValueAt(department.get(i),i,1);
resultTable.setValueAt(salary.get(i),i,2);
}
}

Reading text file from a GUI

I have a GUI that verifies a username and password. The other part of the assignment is to read from a file that contains a username and a password and checks to see if it matches what the user put in the text field. If it does match then it will hide the Login page and another page will appear with a "Welcome" message. I have zero experience with text files, where do I put that block of code? I assume it would go in the ActionListener method and not the main method but i'm just lost. I just need a little push in the right direction. Here is what I have so far. Any help would be greatly appreciated. Thanks!
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
/**
*/
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
listener = new ClickListener();
}
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
}
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}
import javax.swing.*;
import java.awt.*;
/**
*/
public class PassWordFrameViewer
{
public static void main(String[] args)
{
JFrame frame = new PassWordFrame();
frame.setTitle("Password Verification");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
First of all you initialize the listener (listener = new ClickListener()) after the call to #createComponents() method so this means you will add a null listener to the login button. So your constructor should look like this:
public PassWordFrame() {
listener = new ClickListener();
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
Then, because you want to change the GUI with a welcome message, you should use a SwingWorker, a class designed to perform GUI-interaction tasks in a background thread. In the javadoc you can find nice examples, but here is also a good tutorial: Worker Threads and SwingWorker.
Below i write you only the listener implementation (using a swing worker):
class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
new SwingWorker<Boolean, Void>() {
#Override
protected Boolean doInBackground() throws Exception {
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
BufferedReader reader = new BufferedReader(new FileReader(userFile));
String user;
String pass;
try {
user = reader.readLine();
pass = reader.readLine();
}
catch (IOException e) {
//
// in case something is wrong with the file or his contents
// consider login failed
user = null;
pass = null;
//
// log the exception
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// ignore, nothing to do any more
}
}
if (usertext.getText().equals(user) && passtext.getText().equals(pass)) {
return true;
} else {
return false;
}
}
#Override
protected void done() {
boolean match;
try {
match = get();
}
//
// this is a learning example so
// mark as not matching
// and print exception to the standard error stream
catch (InterruptedException | ExecutionException e) {
match = false;
e.printStackTrace();
}
if (match) {
// show another page with a "Welcome" message
}
}
}.execute();
}
}
Another tip: don't add components to a JFrame, so replace this:
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
with:
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(panel1, BorderLayout.NORTH);
contentPane.add(panel2, BorderLayout.WEST);
contentPane.add(panel3, BorderLayout.CENTER);
contentPane.add(panel4, BorderLayout.SOUTH);
setContentPane(contentPane);
assume there is a textfile named password.txt in g driver and it contain usename and password separate by # symbol.
like following
password#123
example code
package homework;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
String info = ReadFile();
System.out.println(info);
String[] split = info.split("#");
String uname=split[0];
String pass =split[1];
if(usertext.getText().equals(uname) && passtext.getText().equals(pass)){
instruct.setText("access granted");
}else{
instruct.setText("access denided");
}
}
});
}
private static String ReadFile(){
String line=null;
String text="";
try{
FileReader filereader=new FileReader(new File("G:\\password.txt"));
//FileReader filereader=new FileReader(new File(path));
BufferedReader bf=new BufferedReader(filereader);
while((line=bf.readLine()) !=null){
text=text+line;
}
bf.close();
}catch(Exception e){
e.printStackTrace();
}
return text;
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}

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