I have spent many hours digging around the web and cannot seem to find a straightforward answer or method to add a dropdown selection into my main panel that houses the various text fields, in this case, I am trying to add a paint color selection to the panel so that color can then be used as a variable in determining cost.
The closest I have come so far is having a combo box popup in a new window but then was unable to retrieve the selection.
package paintestimator;
import java.lang.String;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Component;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.PopupMenu;
import javax.swing.JComboBox;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PaintEstimator extends JFrame
{
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
//Josh
public PaintEstimator()
{
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
JButton ChoiceA = new JButton("Paint Color");
//JComboBox vendorBTN = (new JComboBox());
ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
//box to show chosen color
//mainPanel.add(new JLabel("Color Chosen"));
// mainPanel.add(sColor);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add( new JLabel("Select a Color"));
mainPanel.add (ChoiceA);
// mainPanel.add(sColor);
// Select<String> select = new Select<>();
//select.setLabel("Sort by");
//select.setItems("Most recent first", "Rating: high to low",
// "Rating: low to high", "Price: high to low", "Price: low to high");
//select.setValue("Most recent first");
// mainPanel.add(select);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
// mainPanel.add(ChoiceA);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
//Josh
class CalcChangeBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n); // still need refine decimal point to #.0
(one decimal place)
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f)
{
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// clear text fields and set focus
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
class ChoiceAListener implements ActionListener
{
public void actionPreformed (ActionEvent e)
{
}
public static void main(String[] args)
{
PaintEstimator window = new PaintEstimator();
window.setVisible(true);
}
}
Below is the combo box I was able to create:
public static void main(String[] args)
{
String[] optionsToChoose =
{
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
JFrame jFrame = new JFrame();
JComboBox<String> jComboBox = new JComboBox<>(optionsToChoose);
jComboBox.setBounds(80, 50, 140, 20);
JButton jButton = new JButton("Done");
jButton.setBounds(100, 100, 90, 20);
JLabel jLabel = new JLabel();
jLabel.setBounds(90, 100, 400, 100);
jFrame.add(jButton);
jFrame.add(jComboBox);
jFrame.add(jLabel);
jFrame.setLayout(null);
jFrame.setSize(350, 250);
jFrame.setVisible(true);
jButton.addActionListener((ActionEvent e) ->
{
String selectedColor = "You selected " +
jComboBox.getItemAt(jComboBox.getSelectedIndex());
jLabel.setText(selectedColor);
});
}
Start by reading through How to Use Combo Boxes (and it wouldn't hurt to look over some the examples)
Start by creating an instance field for the combobox...
public class PaintEstimator extends JFrame {
//...
private JComboBox<String> colorChoice = new JComboBox<>();
//...
Next, create a ComboBoxModel to hold the values you want to present and replace the ChoiceA button with the combobox...
mainPanel.add(new JLabel("Select a Color"));
//mainPanel.add(ChoiceA);
// mainPanel.add(sColor);
String[] optionsToChoose = {
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(optionsToChoose);
colorChoice.setModel(model);
mainPanel.add(colorChoice);
And then in your ActionListener, get the selected value...
public void actionPerformed(ActionEvent e) {
try {
String choosenColor = (String) colorChoice.getSelectedItem();
System.out.println("choosenColor = " + choosenColor);
Runnable example...
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new PaintEstimator();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintEstimator extends JFrame {
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
private JComboBox<String> colorChoice = new JComboBox<>();
public PaintEstimator() {
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
//ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add(new JLabel("Select a Color"));
String[] optionsToChoose = {
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(optionsToChoose);
colorChoice.setModel(model);
mainPanel.add(colorChoice);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
class CalcChangeBTNListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String choosenColor = (String) colorChoice.getSelectedItem();
System.out.println("choosenColor = " + choosenColor);
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n);
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f) {
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I keep getting that error no matter what variables I change, and I was wondering If I might of messed up somewhere along my lines.
This is my main class
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class menu implements ActionListener {
/*public static JCheckBox check;
public static JCheckBox check1;*/
public static JPanel panel;
public static JFrame frame;
public static JButton Wallpaper;
public static JButton tile;
public static JButton trim;
public static void main(String[] args) {
panel = new JPanel();
frame = new JFrame();
frame.setSize(350, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(555,318);
frame.add(panel);
Border dash = BorderFactory.createLineBorder(Color.BLACK);
//create the MainMenu title
JLabel MainMenu = new JLabel(" MainMenu");
MainMenu.setBounds(30, 10, 80, 25);
MainMenu.setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.black));
MainMenu.setForeground(Color.black);
panel.add(MainMenu);
//creates the wallpaper button
Wallpaper = new JButton("Wallpaper");
Wallpaper.setBounds(20,40,100,25);
Wallpaper.addActionListener(new menu());
panel.add(Wallpaper);
//creates the tile button
tile = new JButton("Tile");
tile.setBounds(20,70,100,25);
panel.add(tile);
//creates the trim button
trim = new JButton("Trim");
trim.setBounds(20,100,100,25);
trim.addActionListener(new menu());
panel.add(trim);
panel.setLayout(null);
frame.setVisible(true);
//i was playing around do not mind that :)
/* check = new JCheckBox();
check.setBounds(130, 30, 100, 25);
panel.add(check);
check1 = new JCheckBox();
check1.setBounds(130, 50, 100, 25);
panel.add(check1);
check2 = new JCheckBox();
check2.setBounds(130, 70, 100, 25);
panel.add(check2);
*/
}
#Override
public void actionPerformed(ActionEvent e) {
//makes the Trim button actully do something
if (e.getSource() == Wallpaper){
WallpaperCalculator.Wallpaper();
}
if (e.getSource() == trim) {
TrimCalculator.Trim();
}
}
}
Here is my second class where I keep getting the error on line 90
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TrimCalculator implements ActionListener {
private static JTextField lengthText;
private static JTextField widthText;
private static JButton button;
private static JLabel total;
private static JLabel walls;
private static JTextField wallsText;
public static void Trim() {
//creates the gui it self
JPanel panel = new JPanel();
panel.setLayout(null);
JFrame frame = new JFrame();
frame.setSize(350,300);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocation(555,318);
frame.add(panel);
//sets the title
JLabel title = new JLabel();
title.setBounds(10, 20, 300, 25);
title.setText("Trim Calculator");
panel.add(title);
//sets the lengths title
JLabel length = new JLabel();
length.setBounds(10,55,300,25);
length.setText("Length Input");
panel.add(length);
//creates a field for the length text input
lengthText = new JTextField();
lengthText.setBounds(120,55,90,25);
panel.add(lengthText);
//creates a width text label
JLabel width = new JLabel();
width.setBounds(10,80,300,25);
width.setText("Width Input");
panel.add(width);
//created a field for the width text input
widthText = new JTextField();
widthText.setBounds(120,80,90,25);
panel.add(widthText);
//makes a field to set a text box so people can see where the total will be
JLabel totalAmount = new JLabel();
totalAmount.setBounds(10,150,300,25);
totalAmount.setText("Total Amount:");
panel.add(totalAmount);
//makes a field to present the answer
total = new JLabel();
total.setBounds(125, 150, 90,25);
panel.add(total);
walls = new JLabel("Walls");
walls.setBounds(10,105,90,25);
panel.add(walls);
wallsText = new JTextField();
wallsText.setBounds(120,105,90,25);
panel.add(wallsText);
//makes a button to get the two lengths and start the multiplication process
button = new JButton();
button.setBounds(10,130,90,25);
button.setText("Find");
button.setForeground(Color.CYAN);
button.addActionListener(new TrimCalculator());
panel.add(button);
frame.setVisible(true);
}
//gets the button and changes it from a string into a int so it can be calculated
#Override
public void actionPerformed(ActionEvent e) {
String lengthAmount = lengthText.getText();<— line that the error is throwing me to
String widthAmount = widthText.getText();
String wallAmount = wallsText.getText();
//changes the strings into a double
double length = Double.parseDouble(lengthAmount);
double width = Double.parseDouble(widthAmount);
double wallz = Double.parseDouble(wallAmount);
// adds the two sides together
double sides = length + width;
//multiplies sides1 by 2 to get preTotal
double preTotal = sides * 2;
//gets total2 and divides it by 8 to get the final total
double Total = preTotal/8;
//times the total by the walls given.
double newTotal = Total * wallz;
//changes the double variable newTotal into a string
String f = String.valueOf(newTotal);
//makes the button actually print the amount of trim needed
if (e.getSource() == button){
total.setText(f+" ft");
}
}
}
And here is my last class that's where I click the button to try to get an answer but it send me to TrimCalculator for some reason?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WallpaperCalculator implements ActionListener {
private static JTextField lengthText2;
private static JTextField heightText;
private static JButton button2;
private static JLabel total;
public static void Wallpaper() {
JPanel panel = new JPanel();
panel.setLayout(null);
JFrame frame = new JFrame();
frame.setSize(350,300);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocation(555,318);
frame.add(panel);
//sets the title
JLabel title = new JLabel();
title.setBounds(10, 20, 300, 25);
title.setText("Wallpaper Calculator");
title.setForeground(Color.BLUE);
panel.add(title);
//sets the lengths title
JLabel length = new JLabel();
length.setBounds(10,55,300,25);
length.setText("Length Input");
panel.add(length);
//creates a field for the length text input
lengthText2 = new JTextField();
lengthText2.setBounds(120,55,90,25);
panel.add(lengthText2);
//creates a width text label
JLabel height = new JLabel();
height.setBounds(10,80,300,25);
height.setText("height Input");
panel.add(height);
//created a field for the width text input
heightText = new JTextField();
heightText.setBounds(120,80,90,25);
panel.add(heightText);
//makes a field to set a text box so people can see where the total will be
JLabel totalAmount = new JLabel();
totalAmount.setBounds(10,150,300,25);
totalAmount.setText("Total Amount:");
panel.add(totalAmount);
//makes a field to present the answer
total = new JLabel();
total.setBounds(125, 150, 90,25);
panel.add(total);
//makes a button to get the two lengths and start the multiplication process
button2 = new JButton();
button2.setBounds(10,130,90,25);
button2.setText("Find");
button2.setForeground(Color.blue);
button2.addActionListener(new TrimCalculator());
panel.add(button2);
frame.setVisible(true);
}
//gets the button and changes it from a string into a int so it can be calculated
#Override
public void actionPerformed(ActionEvent c) {
String lengthAm = lengthText2.getText();
String heightAm = heightText.getText();
//changes the strings into a double
double length = Double.parseDouble(lengthAm);
double height = Double.parseDouble(heightAm);
// multiplies the two sides
double sidesTotal = length * height;
//divides the sidesTotal to get Total
double Total = sidesTotal / 40;
System.out.println(Total);
//changes the double variable newTotal into a string
String f = String.valueOf(Total);
//makes the button actually print the amount of trim needed
if (c.getSource() == button2){
total.setText(f+" ft");
}
}
}
Thank you again for the help!
I figured it out, but for those that do get the NullPointerException error, if you have many class, then quote/* */ one class all the way out and see where it might be duplicated, if you ever copy and paste code.
There is 3 panels which I created as seen in the image. The first panel is the "From" panel, second is "To" panel, and third is the buttons panel. So the question is, how can I put a new line for the "Enter Temperature: [ ]" so that it will be under neath the radio buttons? I am very new to Java swing/awt please bear with me.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class TemperatureConversion extends JFrame{
// component
JTextField txtFromTemp, txtToTemp;
JLabel lblFromTemp, lblToTemp;
JRadioButton radFromCelsius, radFromFahrenheit, radFromKelvin;
JRadioButton radToCelsius, radToFahrenheit, radToKelvin;
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFromTemp, pnlButton;
ButtonGroup bgFrom, bgTo;
JButton btnConvert, btnExit;
// constructor
public TemperatureConversion(){
super("Temperature");
// assign objects
radFromCelsius = new JRadioButton("Celsius", true);
radFromFahrenheit = new JRadioButton("Fahrenheit");
radFromKelvin = new JRadioButton("Kelvin");
lblFromTemp = new JLabel("Enter Temperature: ");
pnlFromTemp = new JPanel();
btnConvert = new JButton("Convert");
btnExit = new JButton("Exit");
pnlButton = new JPanel();
txtFromTemp = new JTextField(3);
lblToTemp = new JLabel("Comparable Temperature: ");
txtToTemp = new JTextField(3);
// register the button to a listener
btnExit.addActionListener(new MyButtonListener());
btnConvert.addActionListener(new MyButtonListener());
// make the multiple choice exclusive but not a container
bgFrom = new ButtonGroup();
bgFrom.add(radFromCelsius);
bgFrom.add(radFromFahrenheit);
bgFrom.add(radFromKelvin);
// radio buttons
radToCelsius = new JRadioButton("Celsius");
radToFahrenheit = new JRadioButton("Fahrenheit", true);
radToKelvin = new JRadioButton("Kelvin");
// make the multiple choice exclusive
bgTo = new ButtonGroup();
bgTo.add(radToCelsius);
bgTo.add(radToFahrenheit);
bgTo.add(radToKelvin);
pnlFromRadioButton = new JPanel();
pnlToRadioButton = new JPanel();
// decorate the panel
pnlFromRadioButton.setBorder(BorderFactory.createTitledBorder("From"));
pnlToRadioButton.setBorder(BorderFactory.createTitledBorder("To"));
// add radiobutton to panel
pnlFromRadioButton.add(radFromCelsius);
pnlFromRadioButton.add(radFromFahrenheit);
pnlFromRadioButton.add(radFromKelvin);
pnlToRadioButton.add(radToCelsius);
pnlToRadioButton.add(radToFahrenheit);
pnlToRadioButton.add(radToKelvin);
// add button to panel
pnlButton.add(btnConvert);
pnlButton.add(btnExit);
// add label and txt field to panel
pnlFromRadioButton.add(lblFromTemp);
pnlFromRadioButton.add(txtFromTemp);
pnlToRadioButton.add(lblToTemp);
txtToTemp.setEditable(false);
pnlToRadioButton.add(txtToTemp);
// add panels to the frame
add(pnlFromRadioButton, BorderLayout.NORTH);
add(pnlToRadioButton, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
// private inner class to handle button event
private class MyButtonListener implements ActionListener {
// must override actionPerformed method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnConvert) {
if (radFromCelsius.isSelected())
System.out.print("exit");
} else if (e.getSource() == btnExit) {
System.exit(0);
}
}
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
Nest more JPanels and use layout managers
For instance, in the JPanel where you want two lines, give it a BoxLayout oriented along the BoxLayout.PAGE_AXIS, and then add two more JPanels to this BoxLayout-using, a top JPanel with the radio buttons and bottom JPanel with the JLabel and JTextField (or whatever else you want in it).
Side note: this would be a great place to use an enum one called TempScale that had three values: CELSIUS, FAHRENHEIT, KELVIN. You could even give the enum the formulas for conversion to and from Kelvin.
For example:
import java.awt.Component;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class TempConversion2 extends JPanel {
private ToFromPanel fromPanel = new ToFromPanel("From", true);
private ToFromPanel toPanel = new ToFromPanel("To", false);
private ButtonPanel buttonPanel = new ButtonPanel(fromPanel, toPanel);
public TempConversion2() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(fromPanel);
add(toPanel);
add(buttonPanel);
}
private static void createAndShowGui() {
TempConversion2 mainPanel = new TempConversion2();
JFrame frame = new JFrame("Temp Convert");
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());
}
}
#SuppressWarnings("serial")
class ButtonPanel extends JPanel {
public ButtonPanel(ToFromPanel fromPanel, ToFromPanel toPanel) {
add(new JButton(new ConvertAction("Convert", fromPanel, toPanel)));
add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
}
}
#SuppressWarnings("serial")
class ConvertAction extends AbstractAction {
private ToFromPanel fromPanel;
private ToFromPanel toPanel;
public ConvertAction(String name, ToFromPanel fromPanel, ToFromPanel toPanel) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
this.fromPanel = fromPanel;
this.toPanel = toPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
String text = fromPanel.getText();
try {
double fromTemp = Double.parseDouble(text.trim());
TempScale fromScale = fromPanel.getTempScalesPanel().getSelectedTempScale();
double kelvinValue = fromScale.convertToKelvin(fromTemp);
TempScale toScale = toPanel.getTempScalesPanel().getSelectedTempScale();
double toValue = toScale.convertFromKelvin(kelvinValue);
String toValueString = String.format("%.2f", toValue);
toPanel.setText(toValueString);
} catch (NumberFormatException e1) {
Component parentComponent = fromPanel;
String message = "Text must be a valid number: " + text;
String title = "Invalid Text Entered";
int messageType = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(parentComponent, message, title, messageType);
fromPanel.setText("");
}
}
}
#SuppressWarnings("serial")
class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
#SuppressWarnings("serial")
class ToFromPanel extends JPanel {
private String title;
private TempScalesPanel tempScalesPanel = new TempScalesPanel();
private JTextField tempTextField = new JTextField(3);
public ToFromPanel(String title, boolean textFieldEnabled) {
this.title = title;
tempTextField.setFocusable(textFieldEnabled);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
bottomPanel.add(new JLabel("Temperature:"));
bottomPanel.add(Box.createHorizontalStrut(8));
bottomPanel.add(tempTextField);
setBorder(BorderFactory.createTitledBorder(title));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(tempScalesPanel);
add(bottomPanel);
}
public String getTitle() {
return title;
}
public TempScalesPanel getTempScalesPanel() {
return tempScalesPanel;
}
public String getText() {
return tempTextField.getText();
}
public void setText(String text) {
tempTextField.setText(text);
}
}
#SuppressWarnings("serial")
class TempScalesPanel extends JPanel {
private ButtonGroup buttonGroup = new ButtonGroup();
private Map<ButtonModel, TempScale> buttonTempMap = new HashMap<>();
public TempScalesPanel() {
for (TempScale tempScale : TempScale.values()) {
JRadioButton radioButton = new JRadioButton(tempScale.getName());
add(radioButton);
buttonGroup.add(radioButton);
buttonTempMap.put(radioButton.getModel(), tempScale);
// set first button as selected by default
if (buttonGroup.getSelection() == null) {
buttonGroup.setSelected(radioButton.getModel(), true);
}
}
}
public TempScale getSelectedTempScale() {
ButtonModel model = buttonGroup.getSelection();
return buttonTempMap.get(model);
}
}
This is the enum that I was talking about. Note that if you change the enum, and for instance add another temperature scale element, the program will automatically include it in the GUI and in the calculations. God I love Java and OOP.
public enum TempScale {
CELSIUS("Celsius", 1.0, -273.15),
FAHRENHEIT("Fahrenheit", 5.0 / 9.0, -459.67),
KELVIN("Kelvin", 1.0, 0.0);
private TempScale(String name, double ratioToKelvin, double absZero) {
this.name = name;
this.ratioToKelvin = ratioToKelvin;
this.absZero = absZero;
}
private String name;
private double ratioToKelvin;
private double absZero;
public String getName() {
return name;
}
public double getRatioToKelvin() {
return ratioToKelvin;
}
public double getAbsZero() {
return absZero;
}
public double convertToKelvin(double value) {
return (value - absZero) * ratioToKelvin;
}
public double convertFromKelvin(double kelvinValue) {
return (kelvinValue / ratioToKelvin) + absZero;
}
}
Always consider posting an MCVE.
For example you layout can be simplified and demonstrated with :
import java.awt.BorderLayout;
import java.awt.Label;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TemperatureConversion extends JFrame{
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFromTemp, pnlButton;
// constructor
public TemperatureConversion(){
pnlFromRadioButton = new JPanel();
pnlFromRadioButton.add(new Label("From Panel"));
pnlToRadioButton = new JPanel();
pnlToRadioButton.add(new Label("To Panel"));
pnlButton = new JPanel();
pnlButton.add(new Label("Buttons Panel"));
// add panels to the frame
add(pnlFromRadioButton, BorderLayout.NORTH);
add(pnlToRadioButton, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
Suppose you want to an "Enter Temperature: [ ]" label to show in a different "line" under From buttons, your constructor will change to :
public TemperatureConversion(){
//set a layout manger. You could use grid layout
//GridLayout gridLayout = new GridLayout(4, 1);
//Or BoxLayout
BoxLayout boxLayout = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS); // top to bottom
setLayout(boxLayout);
pnlFromRadioButton = new JPanel();
pnlFromRadioButton.add(new Label("From Panel"));
//create a panel to hold the desired label
pnlFromTemp = new JPanel();
pnlFromTemp.add(new JLabel("Enter Temperature: [ ]"));//add label
pnlToRadioButton = new JPanel();
pnlToRadioButton.add(new Label("To Panel"));
pnlButton = new JPanel();
pnlButton.add(new Label("Buttons Panel"));
// add panels to the frame
//the panel will show in the order added
add(pnlFromRadioButton);
add(pnlFromTemp);
add(pnlToRadioButton);
add(pnlButton);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Sorry I am new to forums and am not familiar with posting etiquette for codes #c0der. But using GridLayout solved my problem and I want to show you what I did, it is a big mess but here it is. Here is my bizarre code but don't know how to reduce it any further. This is how it is suppose to look as I wanted and because now I understand what you mean by "Nest more JPanels and use layout managers" #Hovercraft Full of Eels:
my temperature program
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class TemperatureConversion extends JFrame {
// component
JTextField txtFromTemp, txtToTemp;
JLabel lblFromTemp, lblToTemp, lblToTempbox;
JRadioButton radFromCelsius, radFromFahrenheit, radFromKelvin;
JRadioButton radToCelsius, radToFahrenheit, radToKelvin;
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFrom, pnlTo, pnlButton;
JPanel pnlEnterTemp, pnlComparableTemp;
ButtonGroup bgFrom, bgTo;
JButton btnConvert, btnExit;
// constructor
public TemperatureConversion() {
super("Temperature");
// assign objects
radFromCelsius = new JRadioButton("Celsius", true);
radFromFahrenheit = new JRadioButton("Fahrenheit");
radFromKelvin = new JRadioButton("Kelvin");
lblFromTemp = new JLabel("Enter Temperature: ");
pnlFrom = new JPanel();
btnConvert = new JButton("Convert");
btnExit = new JButton("Exit");
pnlButton = new JPanel();
txtFromTemp = new JTextField(3);
lblToTemp = new JLabel("Comparable Temperature: ");
txtToTemp = new JTextField(3);
pnlTo = new JPanel();
pnlEnterTemp = new JPanel();
pnlComparableTemp = new JPanel();
pnlFromRadioButton = new JPanel();
pnlToRadioButton = new JPanel();
// register the button to a listener
btnExit.addActionListener(new MyButtonListener());
btnConvert.addActionListener(new MyButtonListener());
// make the multiple choice exclusive but not a container
bgFrom = new ButtonGroup();
bgFrom.add(radFromCelsius);
bgFrom.add(radFromFahrenheit);
bgFrom.add(radFromKelvin);
// radio buttons
radToCelsius = new JRadioButton("Celsius");
radToFahrenheit = new JRadioButton("Fahrenheit", true);
radToKelvin = new JRadioButton("Kelvin");
// make the multiple choice exclusive
bgTo = new ButtonGroup();
bgTo.add(radToCelsius);
bgTo.add(radToFahrenheit);
bgTo.add(radToKelvin);
pnlFrom.setLayout(new GridLayout(2, 1));
pnlFrom.add(pnlFromRadioButton);
pnlFrom.add(pnlEnterTemp);
pnlTo.setLayout(new GridLayout(2, 1));
pnlTo.add(pnlToRadioButton);
pnlTo.add(pnlComparableTemp);
// decorate the panel
pnlFrom.setBorder(BorderFactory.createTitledBorder("From"));
pnlTo.setBorder(BorderFactory.createTitledBorder("To"));
// add radiobutton to panel
pnlFromRadioButton.add(radFromCelsius);
pnlFromRadioButton.add(radFromFahrenheit);
pnlFromRadioButton.add(radFromKelvin);
pnlToRadioButton.add(radToCelsius);
pnlToRadioButton.add(radToFahrenheit);
pnlToRadioButton.add(radToKelvin);
// add button to panel
pnlButton.add(btnConvert);
pnlButton.add(btnExit);
// add label and txt field to panel
pnlEnterTemp.add(lblFromTemp);
pnlEnterTemp.add(txtFromTemp);
pnlComparableTemp.add(lblToTemp);
txtToTemp.setEditable(false);
pnlComparableTemp.add(txtToTemp);
// add panels to the frame
add(pnlFrom, BorderLayout.NORTH);
add(pnlTo, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
// private inner class to handle button event
private class MyButtonListener implements ActionListener {
// must override actionPerformed method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnConvert) {
if (radFromCelsius.isSelected() && radToFahrenheit.isSelected()) {
int strInput = Integer.parseInt(txtFromTemp.getText());
int celsius = strInput * 9 / 5 + 32;
txtToTemp.setText(Integer.toString(celsius));
} else if (radFromCelsius.isSelected() && radToCelsius.isSelected() ||
radFromFahrenheit.isSelected() && radToFahrenheit.isSelected() ||
radFromKelvin.isSelected() && radToKelvin.isSelected()) {
txtToTemp.setText(txtFromTemp.getText());
} else if (radToCelsius.isSelected() && radFromFahrenheit.isSelected()) {
int strInput = Integer.parseInt(txtFromTemp.getText());
int fahrenheit = (strInput - 32) * 5 / 9;
txtToTemp.setText(Integer.toString(fahrenheit));
} else if (radFromKelvin.isSelected() && radToCelsius.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double celsius = strInput - 273.15;
txtToTemp.setText(Double.toString(celsius));
} else if (radFromKelvin.isSelected() && radToFahrenheit.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double fahrenheit = strInput - 459.67;
txtToTemp.setText(Double.toString(fahrenheit));
} else if (radFromCelsius.isSelected() && radToKelvin.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double celsius = strInput + 273.15;
txtToTemp.setText(Double.toString(celsius));
} else if (radFromFahrenheit.isSelected() && radToKelvin.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double fahrenheit = strInput + 255.37;
txtToTemp.setText(Double.toString(fahrenheit));
}
} else if (e.getSource() == btnExit) {
System.exit(0);
}
}
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
By the way #Hovercraft Full Of Eels, your solution is way more efficient and advanced than my level of thinking. I am newbie to programming in general so bear with me on my messy code and organization lol. I have barely dipped my feet into OOP. I do have a sense of how you used enum for TempScale and I thank you for your suggestion. I will keep these in my notes as references.
The idea behind the code is a simple multiplying game where it generates 2 numbers and I have to input the corret answer.
Basically, my question(s) is(are):
When I do operacao.setOpaque(false); it does nothing, or at least not what I'd expect it to do (http://puu.sh/pyVcE/813aa1843a.png - shouldn't the grey area be pink, since the background is pink?). Same happens with JLabels, the setOpaque(false) leaves a grey background behind the (in this case) numbers.
I have that last commented section because I saw someone around here saying to alter the paint method, and it did work, but caused some weird issues (painted over everything when I started the console, only the JTextField would be clear), and then I "fixed" it with the setOpacity(1); setBackground(pink); - is this a proper way of doing it?
public class Frame extends JFrame {
private JPanel panel, mensagem, operacao;
private JTextArea sucesso;
private JLabel numero1, numero2;
private JTextField resposta;
private Color pink = new Color(255, 213, 224);
//more vars
public Frame() {
super("Jogo de Multiplicar!");
setOpacity(1);
setBackground(pink);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(300, 200);
panel = new JPanel();
mensagem = new JPanel();
operacao = new JPanel();
mensagem.setLayout(new FlowLayout(FlowLayout.CENTER));
operacao.setLayout(new FlowLayout(FlowLayout.CENTER));
sucesso = new JTextArea();
sucesso.setEditable(false);
sucesso.setOpaque(false);
sucesso.setFont(minhaFont2);
Random randomGen = new Random();
while (random1 == 0)
random1 = randomGen.nextInt(10);
while (random2 == 0)
random2 = randomGen.nextInt(10);
res = random1 * random2;
numero1 = new JLabel();
numero2 = new JLabel();
numero1.setText(random1 + " *");
numero2.setText(random2 + " =");
numero1.setOpaque(false);
numero1.setFont(minhaFont);
numero2.setFont(minhaFont);
resposta = new JTextField(2);
resposta.addActionListener(new MinhaAcao());
resposta.setFont(minhaFont);
operacao.add(numero1);
operacao.add(numero2);
operacao.add(resposta);
mensagem.add(sucesso);
operacao.setOpaque(true);
operacao.setBackground(pink);
mensagem.setOpaque(true);
mensagem.setBackground(pink);
//add(panel, BorderLayout.NORTH);
add(operacao);
add(mensagem, BorderLayout.SOUTH);
}/*
public void paint(Graphics g) {
g.setColor(pink);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}*/
You need to textfield to be pink. You may have to do this.
resposta.setOpaque(false);
I have refactored your code like below.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Frame extends JFrame {
private JPanel panel, mensagem, operacao;
private JTextArea sucesso;
private JLabel numero1, numero2;
private JTextField resposta;
private Color pink = new Color(255, 213, 224);
//more vars
public Frame() {
super("Jogo de Multiplicar!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(300, 200);
getContentPane().setBackground(pink);
panel = new TransperantPanel();
mensagem = new TransperantPanel();
operacao = new TransperantPanel();
mensagem.setLayout(new FlowLayout(FlowLayout.CENTER));
operacao.setLayout(new FlowLayout(FlowLayout.CENTER));
sucesso = new JTextArea();
sucesso.setEditable(false);
Random randomGen = new Random();
int random1 =0 , random2 = 0;
while (random1 == 0)
random1 = randomGen.nextInt(10);
while (random2 == 0)
random2 = randomGen.nextInt(10);
int res = random1 * random2;
numero1 = new JLabel();
numero2 = new JLabel();
numero1.setText(random1 + " *");
numero2.setText(random2 + " =");
resposta = new JTextField(2);
resposta.setOpaque(false);
resposta.addActionListener(new MinhaAcao());
numero1.setFont(minhaFont);
numero2.setFont(minhaFont);
resposta.setFont(minhaFont);
operacao.add(numero1);
operacao.add(numero2);
operacao.add(resposta);
mensagem.add(sucesso);
add(operacao);
add(mensagem, BorderLayout.SOUTH);
}
public static void main(String[] args){
Frame f = new Frame();
f.setVisible(true);
}
class TransperantPanel extends JPanel {
public TransperantPanel() {
setOpaque(false);
}
}
}
What i have done is
Setting background to contentPane of the frame.
Created a transparent panel(setting Opaque of the panel to false).
Setting JTextfield's Opaque to false.
I am writing a program for class, and I have about all of it done but one part that is really confusing me.
I have to create a system for flooring that a person can choose the floor type, enter their length and width of their floor and it calculates and produces a order summary.
Now, I am able to get all of this but the calculations correct (and I haven't even started on the database connection because of it.)
My professor is extremely vague in her directions and even the answers to her questions, so as a last ditch effort I thought I would try here.
I cannot for the life of me figure it out so ANY help is greatly appreciated.
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class FloorMart
{
private static JFrame frame = null;
private static Integer cost;
private static String floorSize;
private static String floorType;
private double floorLength;
private double floorWidth;
public static void main(String[] args)
{
frame = new JFrame("FloorMart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(320, 300);
JTabbedPane tPane = new JTabbedPane();
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
panel1.setPreferredSize(new Dimension(200, 200));
JLabel jLabel = new JLabel();
jLabel.setText("Welcome to the FloorMart ordering system! ");
panel1.add(jLabel);
JLabel jLabel1 = new JLabel();
jLabel1.setText("Enter your Name: ");
panel1.add(jLabel1);
JTextField text1 = new JTextField(10);
panel1.add(text1);
JLabel jLabel2 = new JLabel();
jLabel2.setText("Enter your Pnone Number: ");
panel1.add(jLabel2);
JTextField text2 = new JTextField(10);
panel1.add(text2);
tPane.addTab("Customer", panel1);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Floor Type? ");
panel2.add(jLabel);
ButtonGroup group = new ButtonGroup();
JRadioButton RadioButton = new JRadioButton("Carpet - $10 per sq ft", true);
panel2.add(RadioButton);
group.add(RadioButton);
JRadioButton RadioButton1 = new JRadioButton("Hardwood - $20 per sq ft");
panel2.add(RadioButton1);
group.add(RadioButton1);
tPane.addTab("Floor Type", panel2);
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
panel3.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Enter the length and width of your floor! ");
panel3.add(jLabel);
JLabel jLabel3 = new JLabel();
jLabel3.setText("Enter the floor length: ");
panel3.add(jLabel3);
JTextField length = new JTextField(10);
panel3.add(length);
//length.setText(cost.toString()); //
JLabel jLabel4 = new JLabel();
jLabel4.setText("Enter the floor width: ");
panel3.add(jLabel4);
JTextField width = new JTextField(10);
panel3.add(width);
//width.setText(cost.toString()); //
tPane.addTab("Floor Size", panel3);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout());
panel4.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Total Cost: ");
panel4.add(jLabel);
JTextField text3 = new JTextField(10);
panel4.add(text3);
JButton button = new JButton("Order Summary");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JPanel panelNew = new JPanel();
panelNew.setLayout(new BoxLayout(panelNew, BoxLayout.Y_AXIS));
JLabel jLabeln = new JLabel("Order Summary");
JLabel jLabeln1 = new JLabel("Customer Name: " + text1.getText());
JLabel jLabeln2 = new JLabel("Phone Number: " + text2.getText());
JLabel jLabeln3 = new JLabel("Floor Type: " + floorType);
JLabel jLabeln4 = new JLabel("Floor Area: " + floorSize);
JLabel jLabeln5 = new JLabel("Total: $" + new Double(cost) + "0");
JLabel jLabeln6 = new JLabel("Thank you for shopping at FloorMart!");
panelNew.add(jLabeln);
panelNew.add(jLabeln1);
panelNew.add(jLabeln2);
panelNew.add(jLabeln3);
panelNew.add(jLabeln4);
panelNew.add(jLabeln5);
panelNew.add(jLabeln6);
frame.invalidate();
frame.remove(panel1);frame.remove(panel2);frame.remove(panel3);
frame.remove(panel4);
frame.remove(tPane);
frame.add(panelNew);
frame.revalidate();
frame.repaint();
}
});
panel4.add(button);
tPane.addTab("Total", panel4);
ChangeListener changeListener= new ChangeListener()
{
public void stateChanged(ChangeEvent changeEvent)
{
JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource();
int index = sourceTabbedPane.getSelectedIndex();
if(index == 2)
{
double floorLength = Double.parseDouble(length.getText());
double floorWidth = Double.parseDouble(width.getText());
floorSize = floorLength * floorWidth;
if(RadioButton.isSelected())
{
cost = 10; //per sq ft
floorType = RadioButton.getText();
}
else if(RadioButton1.isSelected())
{
cost = 20; //per sq ft
floorType = RadioButton1.getText();
}
text3.setText(cost.toString());
}
}
};
tPane.addChangeListener(changeListener);
frame.add(tPane);
frame.setVisible(true);
}
}
I can see two basic things that needs to be changed:
a. this does not compile (floorSize should be double)
String floorSize;
double floorLength = Double.parseDouble(length.getText());
double floorWidth = Double.parseDouble(width.getText());
floorSize = floorLength * floorWidth;
b. The calculation of floorSize should not be triggered by ChangeListener (which causes the calculation to be done before values are entered).
Use "Order Summary" JButton to trigger the calculation.
Here is a working version of the code. See my comments:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class FloorMart
{
private static JFrame frame = null;
private static Integer cost; //better use int
//////////////////////////////////////
//changed from string to double
private static double floorSize;
////////////////////////////////////
private static String floorType;
private double floorLength;
private double floorWidth;
public static void main(String[] args)
{
frame = new JFrame("FloorMart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(320, 300);
JTabbedPane tPane = new JTabbedPane();
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
panel1.setPreferredSize(new Dimension(200, 200));
JLabel jLabel = new JLabel();
jLabel.setText("Welcome to the FloorMart ordering system! ");
panel1.add(jLabel);
JLabel jLabel1 = new JLabel();
jLabel1.setText("Enter your Name: ");
panel1.add(jLabel1);
JTextField text1 = new JTextField(10);
panel1.add(text1);
JLabel jLabel2 = new JLabel();
jLabel2.setText("Enter your Pnone Number: ");
panel1.add(jLabel2);
JTextField text2 = new JTextField(10);
panel1.add(text2);
tPane.addTab("Customer", panel1);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Floor Type? ");
panel2.add(jLabel);
ButtonGroup group = new ButtonGroup();
JRadioButton RadioButton = new JRadioButton("Carpet - $10 per sq ft", true);
panel2.add(RadioButton);
group.add(RadioButton);
JRadioButton RadioButton1 = new JRadioButton("Hardwood - $20 per sq ft");
panel2.add(RadioButton1);
group.add(RadioButton1);
tPane.addTab("Floor Type", panel2);
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
panel3.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Enter the length and width of your floor! ");
panel3.add(jLabel);
JLabel jLabel3 = new JLabel();
jLabel3.setText("Enter the floor length: ");
panel3.add(jLabel3);
JTextField length = new JTextField(10);
panel3.add(length);
//length.setText(cost.toString()); //
JLabel jLabel4 = new JLabel();
jLabel4.setText("Enter the floor width: ");
panel3.add(jLabel4);
JTextField width = new JTextField(10);
panel3.add(width);
//width.setText(cost.toString()); //
tPane.addTab("Floor Size", panel3);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout());
panel4.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Total Cost: ");
panel4.add(jLabel);
JTextField text3 = new JTextField(10);
panel4.add(text3);
JButton button = new JButton("Order Summary");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
//////////////////////////////////////////////////////////////
//calculation moved to here
double floorLength = Double.parseDouble(length.getText());
double floorWidth = Double.parseDouble(width.getText());
floorSize = floorLength * floorWidth;
if(RadioButton.isSelected())
{
cost = 10; //per sq ft
floorType = RadioButton.getText();
}
else if(RadioButton1.isSelected())
{
cost = 20; //per sq ft
floorType = RadioButton1.getText();
}
text3.setText(cost.toString());
//////////////////////////////////////////////////////////////
JPanel panelNew = new JPanel();
panelNew.setLayout(new BoxLayout(panelNew, BoxLayout.Y_AXIS));
JLabel jLabeln = new JLabel("Order Summary");
JLabel jLabeln1 = new JLabel("Customer Name: " + text1.getText());
JLabel jLabeln2 = new JLabel("Phone Number: " + text2.getText());
JLabel jLabeln3 = new JLabel("Floor Type: " + floorType);
JLabel jLabeln4 = new JLabel("Floor Area: " + floorSize);
///////////////////////////////////////////////////////////////////////////
// changed JLabel jLabeln5 = new JLabel("Total: $" + new Double(cost*floorSize) + "0");
//to:
JLabel jLabeln5 = new JLabel("Total: $" + new Double(cost*floorSize) + "0");
///////////////////////////////////////////////////////////////////////////
JLabel jLabeln6 = new JLabel("Thank you for shopping at FloorMart!");
panelNew.add(jLabeln);
panelNew.add(jLabeln1);
panelNew.add(jLabeln2);
panelNew.add(jLabeln3);
panelNew.add(jLabeln4);
panelNew.add(jLabeln5);
panelNew.add(jLabeln6);
frame.invalidate();
frame.remove(panel1);frame.remove(panel2);frame.remove(panel3);
frame.remove(panel4);
frame.remove(tPane);
frame.add(panelNew);
frame.revalidate();
frame.repaint();
}
});
panel4.add(button);
tPane.addTab("Total", panel4);
/////////////////////////////////
//removed ChangeListener
////////////////////////////////
frame.add(tPane);
frame.setVisible(true);
}
}
I am looking for help to debug this program that I have written there are, no errors but the goal is to create a frame with three panels inside of it each of which has a titled border. I am having difficulty because my prompt requires of me to make 2 constructors and 2 classes so when I call the DailySales class in main I feel it doesn't include the other class.
So basically how can I make the panels show up while still keeping two classes and two constructors and how would I add titled borders to each of the JPanels, sorry but I'm having difficulty with the Oracle tutorial.
import java.awt.*;
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.JPanel;
import javax.swing.JTextField;
public class DailySales extends JPanel {
final int lPizzaPrice = 12;
final int mPizzaPrice = 9;
final int sPizzaPrice = 6;
final int bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza;
String mPizza;
String sPizza;
String bSticks;
int largePizza;
int mediumPizza;
int smallPizza;
int breadSticks;
int totalLargePizza;
int totalMediumPizza;
int totalSmallPizza;
int totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
private FlowLayout dailyFlow;
private Container container;
JLabel lPizzaLabel = new JLabel("Large Pizza");//creating labels
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");//Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(dailyFlow);
subPanel1.add(lPizzaLabel, largeField);
subPanel1.add(mPizzaLabel, mediumField);
subPanel1.add(sPizzaLabel, smallField);
subPanel1.add(bSticksLabel, breadField);
subPanel1.setSize(100, 100);
subPanel2.setLayout(dailyFlow);
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel3.setLayout(dailyFlow);
subPanel3.add(totalSalesLabel, totalSalesField);
subPanel3.add(totalTaxLabel, totalTaxField);
subPanel3.add(netSalesLabel, netSalesField);
subPanel3.add(dailyCostLabel, dailyCostField);
subPanel3.add(profitLabel, profitField);
top.setBackground(Color.red);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
totalSalesField.setEditable(false);//making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() //creating a constructor
{
/**
* The constructor with all the layout informations and operators
*
*
* Also adding all labels, textfields, and buttons to frame. making the
* total field uneditable
*/
JFrame frame = new JFrame();
frame.add(subPanel1);
frame.add(subPanel2);
frame.add(subPanel3);
frame.add(top);
frame.setSize(600, 450);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {//initial button removes all entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {//update button calculates all the inputs and displays everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice * largePizza);
totalMediumPizza = (mPizzaPrice * mediumPizza);
totalSmallPizza = (sPizzaPrice * smallPizza);
totalBreadSticks = (bSticksPrice * breadSticks);
totalLargeField.setText("" + totalLargePizza);
totalMediumField.setText("" + totalMediumPizza);
totalSmallField.setText("" + totalSmallPizza);
totalBreadField.setText("" + totalBreadSticks);
totalSales = (totalLargePizza + totalMediumPizza + totalSmallPizza + totalBreadSticks);
totalTax = (totalSales * tax);
netSales = (totalSales - totalTax);
profit = (netSales - dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit > 0) {
profitLabel.setText("Profit of ");
} else if (profit < 0) {
profitLabel.setText("Loss of ");
} else if (profit == 0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {//close button closes the program when clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}
There's still a lot you can do to make this better, but this works.
public class DailySales extends JPanel {
final int lPizzaPrice = 12, mPizzaPrice = 9, sPizzaPrice = 6, bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza, mPizza, sPizza, bSticks;
int largePizza, mediumPizza, smallPizza, breadSticks, totalLargePizza,
totalMediumPizza, totalSmallPizza, totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
JLabel lPizzaLabel = new JLabel("Large Pizza");
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");// Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(new GridLayout(4, 2));
subPanel1.add(lPizzaLabel);
subPanel1.add(largeField);
subPanel1.add(mPizzaLabel);
subPanel1.add(mediumField);
subPanel1.add(sPizzaLabel);
subPanel1.add(smallField);
subPanel1.add(bSticksLabel);
subPanel1.add(breadField);
subPanel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
// subPanel2.setLayout(new BoxLayout(subPanel2, BoxLayout.Y_AXIS)); // Same as next line
subPanel2.setLayout(new GridLayout(4, 1));
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
subPanel3.setLayout(new GridLayout(5, 2));
subPanel3.add(totalSalesLabel);
subPanel3.add(totalSalesField);
subPanel3.add(totalTaxLabel);
subPanel3.add(totalTaxField);
subPanel3.add(netSalesLabel);
subPanel3.add(netSalesField);
subPanel3.add(dailyCostLabel);
subPanel3.add(dailyCostField);
subPanel3.add(profitLabel);
subPanel3.add(profitField);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
top.setBackground(Color.YELLOW);
totalSalesField.setEditable(false);// making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() // creating a constructor
{
/**
* The constructor with all the layout informations and operators Also
* adding all labels, textfields, and buttons to frame. making the total
* field uneditable
*/
new GUI();
JPanel mainPanel = new JPanel(new GridLayout(2, 2));
mainPanel.add(subPanel1);
mainPanel.add(subPanel2);
mainPanel.add(subPanel3);
JPanel buttonPanel = new JPanel();
buttonPanel.add(clearButton);
buttonPanel.add(calculateButton);
buttonPanel.add(exitButton);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(top, BorderLayout.PAGE_START);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
frame.setSize(600, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {// initial button
// removes all
// entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {// update button
// calculates
// all the
// inputs and
// displays
// everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice*largePizza);
totalMediumPizza = (mPizzaPrice*mediumPizza);
totalSmallPizza = (sPizzaPrice*smallPizza);
totalBreadSticks = (bSticksPrice*breadSticks);
totalLargeField.setText(""+totalLargePizza);
totalMediumField.setText(""+totalMediumPizza);
totalSmallField.setText(""+totalSmallPizza);
totalBreadField.setText(""+totalBreadSticks);
totalSales = (totalLargePizza+totalMediumPizza+totalSmallPizza+totalBreadSticks);
totalTax = (totalSales*tax);
netSales = (totalSales-totalTax);
profit = (netSales-dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit>0) {
profitLabel.setText("Profit of ");
} else if (profit<0) {
profitLabel.setText("Loss of ");
} else if (profit==0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {// close button
// closes the
// program when
// clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}