Welcome everyone,
This is my first post on this website and I am also quite new to java so go easy on me :)
I am working on a project for my college the task is:
"Design & Build a Java application based on a class linked to a swing
(GUI) application. "
So I Decided to go for a shopping app that will allow you to choose a few games, add them to cart and then display the cart / edit it / remove items etc.
I am having problem with adding items to a cart using a JButton. Here is my code:
Driver:
public class Driver {
public static void main (String[] args) {
MainShop shop= new MainShop ("Welcome to my Shop");
}
}
MainShop:
import java.awt.*;
import java.util.*;
import java.text.*;
import java.math.*;
import javax.swing.*;
import java.awt.event.*;
public class MainShop extends JFrame implements ActionListener, WindowListener {
private Container content;
private JLabel l1 = new JLabel ("Welcome to my Shop");
private JLabel l2 = new JLabel("You want to browse for great games?");
private JLabel l3 = new JLabel ("Choose one of the following 2 platforms: ");
private JLabel l4 = new JLabel ("XBox has no good games. Try PS4 :) ");
private PS4 dialog1 = null ;
private XBox dialog2 = null;
private JButton b1 = new JButton("PS4");
private JButton b2 = new JButton("XBox");
public MainShop (String str) {
super(str);
content = getContentPane();
content.setLayout(new GridLayout(2,2));
content.add(l1);
content.add(l2);
content.add(l3);
content.add(l4);
l4.setVisible(false);
content.add(b1);
b1.addActionListener(this);
content.add(b2);
b2.addActionListener(this);
setSize(800, 150);
content.setBackground(Color.white);
this.addWindowListener(this);
setVisible(true);
}
public void actionPerformed (ActionEvent e) {
Object target = e.getSource();
if (target == b2) {
l4.setVisible(true);
}
if (target == b1) {
l4.setVisible(false);
this.setVisible(false);
new PS4(this, "PS4");
}
}
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e){System.exit(0);}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
}
PS4 class
import java.awt.*;
import java.util.*;
import java.text.*;
import java.math.*;
import javax.swing.*;
import java.awt.event.*;
class PS4 extends JFrame implements ActionListener, WindowListener{
private JPanel Center = new JPanel();
private JPanel South = new JPanel ();
private JPanel North = new JPanel ();
private JPanel South1 = new JPanel();
private JPanel South2 = new JPanel();
private JPanel Center1 = new JPanel();
private JPanel Center2 = new JPanel ();
private JPanel Center3 = new JPanel ();
private JLabel n1 = new JLabel ("PS4 Games");
private JLabel c1desc = new JLabel ("Name");
private JLabel li1 = new JLabel ("Like it?");
private JLabel c2desc = new JLabel ("Description");
private JLabel c3desc = new JLabel ("Price");
private JButton basket = new JButton ("Proceed to checkout");
private JButton CB = new JButton("Go Back");
private JLabel g1 = new JLabel("Uncharted");
private JButton b1 = new JButton("Add to Basket");
private JLabel d1 = new JLabel (" Action-adventure ");
private JLabel p1 = new JLabel ("59.99€");
private JLabel g2 = new JLabel("Call of Duty");
private JButton b2 = new JButton("Add to Basket");
private JLabel d2 = new JLabel (" First Person Shooter ");
private JLabel p2 = new JLabel ("69.99€");
private JLabel g3 = new JLabel("Fifa 18");
private JButton b3 = new JButton("Add to Basket");
private JLabel d3 = new JLabel (" Sport ");
private JLabel p3 = new JLabel ("69.99€");
private JLabel g4 = new JLabel("Skyrim");
private JButton b4 = new JButton("Add to Basket");
private JLabel d4 = new JLabel (" Open World RPG ");
private JLabel p4 = new JLabel ("49.99€");
private Container content;
private JFrame parent;
public PS4 (JFrame p, String Str) {
super(Str);
parent = p;
getContentPane().add(North, BorderLayout.NORTH);
North.add(n1);
getContentPane().add(Center, BorderLayout.CENTER);
Center.setLayout(new GridLayout(5,4));
Center.add(c1desc);
Center.add(c2desc);
Center.add(c3desc);
Center.add(li1);
Center.add(g1);
Center.add(d1);
Center.add(p1);
Center.add(b1); b1.addActionListener(this);
Center.add(g2);
Center.add(d2);
Center.add(p2);
Center.add(b2); b2.addActionListener(this);
Center.add(g3);
Center.add(d3);
Center.add(p3);
Center.add(b3); b3.addActionListener(this);
Center.add(g4);
Center.add(d4);
Center.add(p4);
Center.add(b4); b4.addActionListener(this);
getContentPane().add(South, BorderLayout.SOUTH);
South.setLayout(new GridLayout(1,2));
South.add(South1);
South.add(South2);
South1.add(CB);
CB.addActionListener(this);
South2.add(basket);
basket.addActionListener(this);
setSize(600,400);
setVisible(true);
this.addWindowListener(this);
}
public void actionPerformed(ActionEvent e) {
Object target = e.getSource();
if (target == b1) {
// THIS IS WHERE I STRUGGLE
}
if (target == b2) {
}
if (target == b3) {
}
if(target == b4) {
}
if(target==CB) {
this.setVisible(false);
parent.setVisible(true);;
}
if (target == basket) {
this.setVisible(false);
new Checkout(this, "");
}
}
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e){System.exit(0);}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
}
So how do I Add the items I want to a new class by clicking the "Add to cart" JButton?
The worst thing is that we have to present it in 2 weeks and it was given to us on our last class on Friday before eastern break. So we literally have 2 weeks to work on it without any help of our lecturers.
Also, please do not worry about the code structure/layout etc as this will be done at the very end. Right now I'm trying to get the code working.
Now, I know its a long post so any suggestions would be appreciated
If anyone needs screenshots just let me know and I will add them.
Thanks!
I’m currently on my phone, so this answer will be brief for now, however I can help more if required when I get home.
Two options come to mind immediately.
You could create an ArrayList called something like “basket” and add an item to the list, depending on which item’s “add to basket” button you press.
Create a custom object of your own, and use that as the shopping basket.
Related
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.
I'm currently making our project and I'm having problem reseting JLabel back to "0". Here's the code
main code snippet (check note 1 for frame disposal method used):
import javax.swing.*; //import library
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class draft_main //class name
{
public static void main(String[] args)
{ //method name
JFrame f0 = new JFrame("POS"); //frame
JPanel p0 = new JPanel(); //panel inside the frame
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
JPanel p6 = new JPanel();
JPanel p7 = new JPanel();
JLabel l0 = new JLabel("Amount:"); //label inside the panel
JLabel l1 = new JLabel("0");
JLabel l2 = new JLabel("Menu Code: ");
JLabel l3 = new JLabel("--Menu--");
JTextField tf0 = new JTextField("", 12); //user input for menu code
JButton b0 = new JButton("Checkout"); //buttons
JButton b1 = new JButton("Cancel");
JButton b2 = new JButton("Exit");
JButton b4 = new JButton("Accept");
JButton b7 = new JButton("Remove");
JOptionPane jop = new JOptionPane(); //JOptionPane
JTextField tf1 = new JTextField("1. Hot Pockets Pizza", 20); //list of menu
JTextField tf2 = new JTextField("2. Burger with Fries", 20);
JTextField tf3 = new JTextField("3. Sticky Rice (Bico)", 20);
ArrayList<String> ar = new ArrayList<String>(); //list of array
try{
b4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) //what the accept button does
{
String order = tf0.getText(), tots="", temp="";
int o = Integer.parseInt(order);
int tot=0;
switch(o) //menu choice
{
case 1 : temp = l1.getText(); tot=Integer.parseInt(temp); tot=tot+250; tots = Integer.toString(tot); l1.setText(tots); ar.add("Hot Pockets Pizza"); break;
case 2 : temp = l1.getText(); tot=Integer.parseInt(temp); tot=tot+65; tots = Integer.toString(tot); l1.setText(tots); ar.add("Burger with Fries"); break;
case 3 : temp = l1.getText(); tot=Integer.parseInt(temp); tot=tot+12; tots = Integer.toString(tot); l1.setText(tots); ar.add("Sticky Rice (Bico)"); break;
default : jop.showMessageDialog(null, "Menu code not listed in menu", "Error", jop.INFORMATION_MESSAGE); break;
}
}
});
b0.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) //what the checkout button does
{
JFrame f1 = new JFrame("Checkout");
JFrame f2 = new JFrame("Order");
JPanel p8 = new JPanel();
JPanel p9 = new JPanel();
JPanel p10 = new JPanel();
JPanel p11 = new JPanel();
JPanel p12 = new JPanel();
JPanel p13 = new JPanel();
JPanel p14 = new JPanel();
JLabel l5 = new JLabel("Order list");
JLabel l6 = new JLabel(/*convert ArrayList to String then put here*/);
JLabel l4 = new JLabel("Cash");
JTextField tf4 = new JTextField("", 14);
JButton b5 = new JButton("Accept");
JButton b6 = new JButton("Cancel");
JButton b7 = new JButton("Ok");
b5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String cas = l1.getText(), in = tf4.getText();
int cash = Integer.parseInt(cas), inp = Integer.parseInt(in), cahs=0;
if(cash>inp)
{
jop.showMessageDialog(null, "Insufficient funds", "Lacking cash? Work for it.", jop.INFORMATION_MESSAGE);
}
else if(cash<inp)
{
cahs = inp - cash;
jop.showMessageDialog(null, "Change: " +cahs+". Thank you");
f1.dispatchEvent(new WindowEvent(f1, WindowEvent.WINDOW_CLOSING));
}
else if(cash==inp)
{
jop.showMessageDialog(null, "Thank you.", "Thank you.", jop.INFORMATION_MESSAGE);
f1.dispatchEvent(new WindowEvent(f1, WindowEvent.WINDOW_CLOSING));
}
}
});
b6.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f1.dispatchEvent(new WindowEvent(f1, WindowEvent.WINDOW_CLOSING));
}
});
b7.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f2.dispatchEvent(new WindowEvent(f2, WindowEvent.WINDOW_CLOSING));
}
});
p9.add(l0);
p9.add(l1);
p10.add(l4);
p10.add(tf4);
p11.add(b5);
p11.add(b6);
p12.add(l5);
p12.add(l6);
p13.add(b7);
p14.add(p12);
p14.add(p13);
p8.add(p10);
p8.add(p11);
p8.add(p9);
f1.add(p8);
f1.pack();
f1.setSize(240,170);
f1.setLocationRelativeTo(null);
f1.setResizable(false);
f1.setDefaultCloseOperation(f1.DISPOSE_ON_CLOSE);
f1.setVisible(true);
f2.add(p14);
f2.pack();
f2.setSize(270,100);
f2.setResizable(false);
f2.setLocationRelativeTo(null);
f2.setDefaultCloseOperation(f2.DISPOSE_ON_CLOSE);
f2.setVisible(true);
}
});
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
l1.setText("0");
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f0.dispose();
}
});
}
catch(Exception e)
{
jop.showMessageDialog(null, "Error");
}
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
p4.add(tf1);
p5.add(tf2);
p6.add(tf3);
p7.add(l3);
p3.add(l2);
p3.add(tf0);
p3.add(b4);
p1.add(l0);
p1.add(l1);
p2.add(b0);
p2.add(b1);
p2.add(b2);
p0.add(p3);
p0.add(p1);
p0.add(p2);
p0.add(p7);
p0.add(p4);
p0.add(p5);
p0.add(p6);
f0.add(p0);
f0.pack();
f0.setSize(303,280);
f0.setLocationRelativeTo(null);
f0.setResizable(false);
f0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f0.setVisible(true);
}
}
what happens is when the main window opens it asks for which from the menu did a guy order then it displays the price. During checkout the user will be asked to input amount of cash given and gives change if there's any. After then the checkout frame is then "properly" disposed (so as I think so), exposing the main frame. However the JLabel does not seem to update when I place another order or clear the current order and it bothers me since the main frame is supposed to be fully interactive until the main frame is closed.
note #1: I have used different methods on how to dispose the 2nd and 3rd frame which pops up since I thought it may have been because of the dispose(); does not really destroys the frame but let's it run in the background.
note #2: yes the program is not finished yet, but those don't matter for now for those will just be some minor features of the application.
You've several problems with this code, but the major ones that I see (and I haven't gone through all of it yet, so there may be more)
First and foremost, those JFrame sub-windows shouldn't be JFrames at all, but rather should be modal JDialogs. The reason for this is this gives you complete control over program flow when these dialogs are used, since you'll then know that the main program flow will be put on hold while the modal dialog is visible, and then the flow will resume as soon as the dialog is no longer visible. This way you can query the state of the dialog after it has been dealt with, and then use this information to update your GUI.
Your amount is shown in the l1 variable, and this will never change unless you specifically call setText(...) on this variable. You don't seem to be doing it when the order has been processed. Again modal dialogs will help you with this.
Your variable naming is bad. Instead of using meaningless letters and numbers for names, use names that make sense and that make your code self-commenting. So for instance, instead of l1, use amountLabel or something similar.
Your code is one huge god class with everything stuffed into the static main method, and this makes for a debugging nightmare. Java is an object-oriented language, and if used properly OOP techniques can help you reduce program complexity making your code easier for yourself and for us to understand. Start OOP-ifying your program and you'll see immediate dividends.
And I found your bug -- you're adding the l1 JLabel to another container, and so it is effectively being removed from the original JFrame. If you minimize your original GUI and then restore it, you'll see the amount l1 JLabel disappear.
Here's some sample code not yet done, but to give you an idea about adding OOP to the program:
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class Draft2 extends JPanel {
private List<MyItem> selectedItems = new ArrayList<>();
private NumberFormat formatter = NumberFormat.getCurrencyInstance();
private double total;
private JLabel totalAmountLabel = new JLabel(formatter.format(total));
private DefaultComboBoxModel<MyItem> comboModel = new DefaultComboBoxModel<>();
private JComboBox<MyItem> menuCombo = new JComboBox<>(comboModel);
public Draft2() {
// monospaced to make names and price line up
menuCombo.setFont(new Font(Font.MONOSPACED, Font.BOLD, 12));
// fill the JComboBox with items
comboModel.addElement(new MyItem("Baseball", 21.5));
comboModel.addElement(new MyItem("Bat", 50.8));
comboModel.addElement(new MyItem("Football", 22.26));
// create a JPanel to hold selection components and add components
JPanel selectionPanel = new JPanel();
selectionPanel.add(new JLabel("Menu:"));
selectionPanel.add(menuCombo);
selectionPanel.add(new JButton(new AcceptAction("Accept", KeyEvent.VK_A)));
// create a JPanel to hold the total amount information
JPanel totalAmountPanel = new JPanel();
totalAmountPanel.add(new JLabel("Total Amount:"));
totalAmountPanel.add(totalAmountLabel);
// create a JPanel to hold buttons, uses grid layout with a single row
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
btnPanel.add(new JButton(new CheckOutAction("Check Out", KeyEvent.VK_C)));
btnPanel.add(new JButton(new CancelAction("Cancel", KeyEvent.VK_N)));
btnPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(selectionPanel);
add(Box.createVerticalStrut(5)); // so don't crowd things
add(totalAmountPanel);
add(Box.createVerticalStrut(5));
add(btnPanel);
}
public void setTotalAmount(double total) {
totalAmountLabel.setText(formatter.format(total));
}
private class AcceptAction extends AbstractAction {
public AcceptAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
MyItem myMenuItem = (MyItem) menuCombo.getSelectedItem();
if (myMenuItem == null) {
return; // nothing selected, get out
}
selectedItems.add(myMenuItem);
double total = 0.0;
for (MyItem myItem : selectedItems) {
total += myItem.getCost();
}
setTotalAmount(total);
}
}
private class CheckOutAction extends AbstractAction {
public CheckOutAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Finish....
// open JDialog or JOptionPane
}
}
private class CancelAction extends AbstractAction {
public CancelAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Finish...
}
}
private class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("My GUI Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Draft2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
class MyItem {
private NumberFormat formatter = NumberFormat.getCurrencyInstance();
private String name;
private double cost;
public MyItem(String name, double cost) {
this.name = name;
this.cost = cost;
}
public String getName() {
return name;
}
public double getCost() {
return cost;
}
#Override
public String toString() {
return String.format("%-10s %s", name, formatter.format(cost));
}
}
I'm doing a project for my class and I'm working on the GUI right now. I don't have much because, well, it's not showing up and it's infuriating. Here's my code.
public class BookQuizGUI extends JFrame implements ActionListener
{
private Container c;
private JPanel pnlButtons;
private JButton addQs;
private JButton takeQuiz;
private JButton quit;
private Container c2;
private JPanel pnlButtons2;
private JComboBox qType;
private JComboBox ans;
private JTextField q;
private JTextField cA;
private JTextField cB;
private JTextField cC;
private JTextField cD;
private JButton add;
private JButton writeAll;
private JButton done;
/**
*
*/
public BookQuizGUI()
{
//The main screen for when the program starts
c = getContentPane();
pnlButtons = new JPanel();
pnlButtons.setLayout(new GridLayout(1, 3));
addQs = new JButton("Add Questions");
takeQuiz = new JButton("Take Quiz");
quit = new JButton("Quit");
setTitle("Book Quiz");
setSize(800, 400);
setLocation(400, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pnlButtons.add(addQs);
pnlButtons.add(takeQuiz);
pnlButtons.add(quit);
addQs.addActionListener(this);
takeQuiz.addActionListener(this);
quit.addActionListener(this);
c.add(pnlButtons, BorderLayout.NORTH);
c.setVisible(true);
//The screen for when the user presses "Add questions"
c2 = getContentPane();
pnlButtons2 = new JPanel();
qType = new JComboBox();
qType.addItem("Elementary Question");
qType.addItem("Standard Question");
qType.addItem("Advanced Question");
pnlButtons2.add(qType);
}
/**
* #param args
*/
public static void main(String[] args)
{
BookQuizGUI gui = new BookQuizGUI();
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == quit)
{
System.exit(0);
}
else if(e.getSource() == addQs)
{
c2.setVisible(true);
}
}
}
Another fundamental question of mine is how to go about switching between GUI screens? This code is supposed to have like a book quiz and you can add questions. Do I just make one container not visible and another visible?
You need to pack it and set it to be visible!
frame.pack();
frame.setVisible(true);
As for answering your second question, why not just change the elements and repaint() the screen, if I understand you want it to be like a quiz with multiple questions, right?
I have a class here that when I try to run gives me the error:
The type GUI must implement the inherited abstract method ActionListener.actionPerformed(actionEvent)
void is an invalid type for the variable actionPerformed
Syntax error on token "(", ; expected
Syntax error on token ")", ; expected
I don't understand what I'm doing wrong at this point. I have my GUI class implementing ActionListener. Any help would be greatly appreciated. Thanks!
GUI Class:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Enumeration;
public class GUI extends JFrame implements ActionListener {
// RadioButtons & ButtonGroup
private JRadioButton jrbStudent = new JRadioButton("Student");
private JRadioButton jrbGraduate = new JRadioButton("Graduate Student");
private ButtonGroup group = new ButtonGroup();
// JTextFields
private JTextField name = new JTextField(20);
private JTextField address = new JTextField(20);
private JTextField balance = new JTextField(20);
private JTextField major = new JTextField(20);
// Submit Button
private JButton jbtSubmit = new JButton("Submit");
// echoStudent output area
private JTextArea echoStudent = new JTextArea();
// Specific Buttons
private JButton printStudentNames = new JButton("Print Student's Names");
private JButton printGradStudentNames = new JButton(
"Print Graduate Student's Names");
private JButton calcBalance = new JButton(
"Calculate Average Balance of All Students");
private JButton compSciMajor = new JButton(
"Displays Computer Science Major Students");
// ScrollPane
private JScrollPane scrollPane = new JScrollPane(echoStudent);
private Manager m1 = new Manager();
public GUI () {
super("College Admission Information Interface");
// Creates panel P1 and adds the components
JPanel p1 = new JPanel(new GridLayout(9, 1, 10, 10));
p1.add(new JLabel("Name: "));
p1.add(name);
p1.add(new JLabel("Address: "));
p1.add(address);
p1.add(new JLabel("Balance: "));
p1.add(balance);
p1.add(new JLabel("Major: "));
p1.add(major);
p1.add(jrbStudent);
p1.add(jrbGraduate);
p1.add(new JLabel("Submit Button: "));
p1.add(jbtSubmit);
p1.add(printStudentNames);
p1.add(printGradStudentNames);
p1.add(calcBalance);
p1.add(compSciMajor);
p1.add(new JLabel("Submitted Text: "));
// Creates a radio-button group to group both buttons
group.add(jrbStudent);
group.add(jrbGraduate);
// Registers listeners
jrbStudent.addActionListener(this);
jrbGraduate.addActionListener(this);
jbtSubmit.addActionListener(this);
printStudentNames.addActionListener(this);
printGradStudentNames.addActionListener(this);
calcBalance.addActionListener(this);
compSciMajor.addActionListener(this);
// GUI settings
setTitle("Information Interface");
setSize(1200, 900);
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
// Adds the panel and text area to the frame
add(p1);
p1.add(echoStudent);
echoStudent.setEditable(false);
public void actionPerformed(ActionEvent event) {
if(event.getSource() == jbtSubmit) {
if(jrbStudent.isSelected()) {
Student s1 = Manager.instance().createStudent(name.getText(),
address.getText(), major.getText(),
Double.parseDouble(balance.getText()));
echoStudent.append("\n\nCreated Student: " + s1.toString());
}
else if(jrbGraduate.isSelected()) {
GradStudent g1 = Manager.instance().createGradStudent(name.getText(),
address.getText(), major.getText(),
Double.parseDouble(balance.getText()));
echoStudent.append("\n\nCreated Graduate Student: " + g1.toString());
}
}
else if(event.getSource() == printStudentNames) {
echoStudent.append(Manager.instance().listStudents());
}
else if(event.getSource() == printGradStudentNames) {
echoStudent.append(Manager.instance().listGrads());
}
else if(event.getSource() == calcBalance) {
echoStudent.append(Manager.instance().aveBalance());
}
else if(event.getSource() == compSciMajor) {
echoStudent.append(Manager.instance().listCsci());
}
}
}
public static void main(String[] args) {
new GUI();
}
}
You need to move your actionPerformed declaration outside of your constructor.
Currently you have this:
public class GUI extends JFrame implements ActionListener {
...
public GUI() {
...
public void actionPerformed(ActionEvent event) {
...
}
}
}
It needs to be like:
public class GUI extends JFrame implements ActionListener {
...
public GUI() {
...
}
public void actionPerformed(ActionEvent event) {
...
}
}
I have not tested your code but that is the first obvious problem.
How do I fetch the selected option from a group of radio buttons.What are the possible ways to check the selected option with the correct answer?
(am a beginner)This is the code which am working on.Just included 2 questions with 4 radio buttons each and they were grouped.Now I have to display a score after checking for the correct answer
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MyRadioButton {
private JFrame frame = new JFrame("RadioRadio");
private JLabel timerl = new JLabel("Press Button to start");
private JPanel butp = new JPanel();
private JPanel panel1=new JPanel();
private JLabel q1=new JLabel("Qn 1:Who is the first President Of India?");
private JLabel q2=new JLabel("Qn 2:Who is the first Prime Minister Of India?");
private JPanel panel2=new JPanel();
private JPanel panel3=new JPanel();
private JLabel label=new JLabel();
private JButton button = new JButton("Start Exam");
private JRadioButton rd1=new JRadioButton("a)Nehru");
private JRadioButton rd2=new JRadioButton("b)R.Prasad");
private JRadioButton rd3=new JRadioButton("c)S.R.Krishnan");
private JRadioButton rd4=new JRadioButton("d)GV.Mavlankar");
private JRadioButton rd5=new JRadioButton("a)Nehru");
private JRadioButton rd6=new JRadioButton("b)R.Prasad");
private JRadioButton rd7=new JRadioButton("c)S.R.Krishnan");
private JRadioButton rd8=new JRadioButton("d)GV.Mavlankar");
ButtonGroup group1 = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
public int result=0;
private Timer mytimer;
private String ss = "Time Remaining %02d Seconds!";
private int elapsedSeconds = 0;
private int total = 60;
JLayeredPane pane=new JLayeredPane();
public MyRadioButton() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (mytimer != null && mytimer.isRunning()) {
//String t = String.format("Result:Your Score is %d", result);
//label.setText(t);
mytimer.stop();
elapsedSeconds = 0;
timerl.setText("Exam Terminated");
} else {
panel1.setBounds(0, 100, 500, 100);
panel1.add(q1);
pane.add(panel1,pane.DEFAULT_LAYER);
panel2.setBounds(0,200,500,100);
panel2.add(q2);
pane.add(panel2,pane.DEFAULT_LAYER);
panel3.setBounds(0, 300, 500, 100);
pane.add(panel3,pane.DEFAULT_LAYER);
panel3.add(label);
panel1.add(rd1);
panel1.add(rd2);
panel1.add(rd3);
panel1.add(rd4);
panel2.add(rd5);
panel2.add(rd6);
panel2.add(rd7);
panel2.add(rd8);
group1.add(rd1);
group1.add(rd2);
group1.add(rd3);
group1.add(rd4);
group2.add(rd5);
group2.add(rd6);
group2.add(rd7);
group2.add(rd8);
mytimer = new Timer(1000, new TimerListener());
mytimer.start();
String t = String.format(ss, total);
timerl.setText(t);
}
}
});
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.add(pane);
butp.setBounds(0,0,500,100);
butp.add(button);
butp.add(timerl);
pane.add(butp,pane.DEFAULT_LAYER);
frame.setVisible(true);
}
private class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
elapsedSeconds++;
if (elapsedSeconds == total) {
mytimer.stop();
elapsedSeconds = 0;
timerl.setText("Time Up");
} else {
String t = String.format(ss, total - elapsedSeconds);
timerl.setText(t);
}
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
MyRadioButton r = new MyRadioButton();
}
});
}
}
You can add an ActionListener to each button in which you can set, for example, class field to currently selected radio button value.
...
String firstAnswer;
String secondAnswer;
...
private FirstQuestionActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
firstAnswer = e.getActionCommand();
}
}
private SecondQuestionActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
secondAnswer = e.getActionCommand();
}
}
And use it this way: rb1.addActionListener(new FirstQuestionActionListener());