I'm writing a small body weight program for my assignment. I have 2 JRadioButton for gender, and five JRadioButtons for the heightt categories. I added an ActionListener for each of these buttons.
In the actionPerformed function, how can I put an an if() condition that lets me decide on the ideal weight based on both the gender and the height?
if(e.getSource() == genderM && e.getSource() == h60 )
doesn't seem to be working.
The problem specifically states that it should be done without a submit button.
This is the code im working with:
public class IdealWeight extends JFrame implements ActionListener {
JLabel lblHeight;
JLabel lblGender;
JLabel lblIdeal;
JRadioButton genderM;
JRadioButton genderF;
JRadioButton h60;
JRadioButton h64;
JRadioButton h68;
JRadioButton h72;
JRadioButton h76;
JTextField txtIdealWeight;
public IdealWeight(){
super("Ideal Wight");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
p1.setLayout(new GridLayout(3,1));
p2.setLayout(new GridLayout(6,1));
lblGender = new JLabel("Your gender: ");
lblHeight = new JLabel("Your height: ");
lblIdeal = new JLabel("Your ideal weight: ");
this.setLayout(new GridLayout(2,3));
ButtonGroup genderGroup = new ButtonGroup();
ButtonGroup weightGroup = new ButtonGroup();
genderM = new JRadioButton("Male: ");
genderM.addActionListener(this);
genderF = new JRadioButton("Female: ");
genderF.addActionListener(this);
h60 = new JRadioButton("60 to 64 inches");
h60.addActionListener(this);
h64 = new JRadioButton("64 to 68 inches");
h64.addActionListener(this);
h68 = new JRadioButton("68 to 72 inches");
h68.addActionListener(this);
h72 = new JRadioButton("72 to 76 inches");
h72.addActionListener(this);
h76 = new JRadioButton("76 to 80 inches");
h76.addActionListener(this);
txtIdealWeight = new JTextField();
txtIdealWeight.setEditable(false);
txtIdealWeight.setColumns(5);
genderGroup.add(genderM);
genderGroup.add(genderF);
weightGroup.add(h60);
weightGroup.add(h64);
weightGroup.add(h68);
weightGroup.add(h72);
weightGroup.add(h76);
p1.add(lblGender);
p1.add(genderM);
p1.add(genderF);
p2.add(lblHeight);
p2.add(h60);
p2.add(h64);
p2.add(h68);
p2.add(h72);
p2.add(h76);
p3.add(lblIdeal);
p3.add(txtIdealWeight);
this.add(p1);
this.add(p2);
this.add(p3);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(new Dimension(400,400));
}
Since the user needs to enter information in all fields before it can be accurately processed, I'd not use ActionListeners on your JCheckBoxes or JRadioButtons, but rather have a single JButton, say called submitButton and then extract the data from your GUI within its ActionListener.
You can get the selected item from each of the ButtonGroup objects that you're using, since it will return the ButtonModel of the JRadioButton selected, or null if nothing has been selected.
If you need more help -- please ask and also edit your question to show us more pertinent code.
Edit
You state in comment:
The problem specifically states that it should be done without a submit button
This is key information that should be part of your original question.
Then use one single ActionListener, and don't worry about the source. Instead in the ActionListener, either query all the JRadioButtons as to their state, and then act on it, or get the models out of your ButtonGroups and do the same.
For example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TwoButtonGroups extends JPanel {
public static final String[] LABELS_1 = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
public static final String[] LABELS_2 = {"Fubar", "Snafu", "DILLIGAF"};
private ButtonGroup buttonGroup1 = new ButtonGroup();
private ButtonGroup buttonGroup2 = new ButtonGroup();
public TwoButtonGroups() {
JPanel panel1 = new JPanel(new GridLayout(0, 1));
JPanel panel2 = new JPanel(new GridLayout(0, 1));
MyActionListener myActionListener = new MyActionListener();
for (String label1 : LABELS_1) {
JRadioButton radioButton = new JRadioButton(label1);
radioButton.setActionCommand(label1);
radioButton.addActionListener(myActionListener);
buttonGroup1.add(radioButton);
panel1.add(radioButton);
}
for (String label2 : LABELS_2) {
JRadioButton radioButton = new JRadioButton(label2);
radioButton.setActionCommand(label2);
radioButton.addActionListener(myActionListener);
buttonGroup2.add(radioButton);
panel2.add(radioButton);
}
add(panel1);
add(panel2);
}
private class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
ButtonModel model1 = buttonGroup1.getSelection();
ButtonModel model2 = buttonGroup2.getSelection();
if (model1 == null || model2 == null) {
return; // not selected
}
System.out.printf("Selections: %s and %s%n", model1.getActionCommand(), model2.getActionCommand() );
}
}
private static void createAndShowGui() {
TwoButtonGroups mainPanel = new TwoButtonGroups();
JFrame frame = new JFrame("TwoButtonGroups");
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(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
The condition
e.getSource() == genderM && e.getSource() == h60
Can never return true because the source is either genderM or h60. Perhaps you meant logical OR.
e.getSource() == genderM || e.getSource() == h60
As an alternative, I'd ignore the source of the event, and use the state of the components instead..
#Override
public void actionPerformed(ActionEvent e) {
if (genderM.isSelected() && h60.isSelected()) {
}
}
Related
As stated in the title i need to move the label for the text box to be above the box and not to the side. attached i have a picutres of what i mean. what i have vs what i want i have tried searching for it but i cannot seem to find the answer im looking for/not exactly sure what to look up. I have tried using JFrame but it made a separate window unless i need to make the entire GUI a JFrame for me to get the result i want?
Also the actionPerformed method has things but it is irrelevant to the question but displays correctly still.
import java.awt.event.\*;
import javax.swing.\*;
import java.text.DecimalFormat;
public class Project4 extends JFrame implements ActionListener {
private JTextArea taArea = new JTextArea("", 30, 20);
ButtonGroup group = new ButtonGroup();
JTextField name = new JTextField(20);
boolean ch = false;
boolean pep = false;
boolean sup = false;
boolean veg = false;
DecimalFormat df = new DecimalFormat("##.00");
double cost = 0.0;
public Project4() {
initUI();
}
public final void initUI() {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
getContentPane().add(panel1, "North");
getContentPane().add(panel2, "West");
getContentPane().add(panel3, "Center");
getContentPane().add(panel4, "East");
panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
getContentPane().add(panel5, "South");
JButton button = new JButton("Place Order");
button.addActionListener(this);
panel5.add(button);
JButton button2 = new JButton("Clear");
button2.addActionListener(this);
panel5.add(button2);
panel3.add(taArea);
JCheckBox checkBox1 = new JCheckBox("Cheese Pizza") ;
checkBox1.addActionListener(this);
panel4.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Pepperoni Pizza");
checkBox2.addActionListener(this);
panel4.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox("Supreme Pizza");
checkBox3.addActionListener(this);
panel4.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox("Vegetarian Pizza");
checkBox4.addActionListener(this);
panel4.add(checkBox4);
JRadioButton radioButton1 = new JRadioButton("Pick Up");
group.add(radioButton1);
radioButton1.addActionListener(this);
panel1.add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Delivery");
group.add(radioButton2);
radioButton2.addActionListener(this);
panel1.add(radioButton2);
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
panel5.add(name_label);
panel5.add(name);
setSize(600, 300);
setTitle("Pizza to Order");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent action) {
}
public static void main(String[] args) {
Project4 ex = new Project4();
ex.setVisible(true);
}
}
You can use a nested JPanel with another layout in order to achieve that. I would go with BorderLayout here. You can also other layouts that allow vertical orientation. Visiting the visual guide to Layout Managers will help you spot them.
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
JPanel verticalNestedPanel = new JPanel(new BorderLayout());
verticalNestedPanel.add(name_label, BorderLayout.PAGE_START);
verticalNestedPanel.add(name, BorderLayout.PAGE_END);
panel5.add(verticalNestedPanel);
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));
}
}
So I'm making a program that finds out the surface area and the volume of polyhedrons, so I need to use JRadioButtons to let the user select what shape they want, if they want SurfaceArea or Volume, and stuff like that.
However, I ran into a problem that requires me to make something run every time that a new button is clicked.
When I added an actionListener() to my JRadioButton, the actionPerformed() method didn't even run. Is there something that I am missing?
I want my actionPerformed()method to run.
width.addActionListener(ral);
height.addActionListener(ral);
length.addActionListener(ral);
slantHeight.addActionListener(ral);
radius.addActionListener(ral);
displayAnswer.addActionListener(ral);
public void actionPerformed(ActionEvent a) {
System.out.println("Changed Radio Button: " + a.getSource());
}
From How to Write an Item Listener (emphasis mine):
Item events are fired by components that implement the ItemSelectable interface. Generally, ItemSelectable components maintain on/off state for one or more items.
Since a radio button fits this description, ItemListener would be a more suitable listener to use; try that instead.
Hope this helps!
Just FYI, this is what I mean by a small-"ish" compilable runnable program that demonstrates a problem. Here I demonstrate not adding action listeners or any listeners to JRadioButtons but rather adding a single listener to a JButton (actually an AbstractAction which is like an ActionListener on steroids). This uses ButtonGroup objects to allow only one JRadioButton to be selected per group, and to allow the code to query which button was selected. The ButtonGroup will return the "model" for the selected JRadioButton, and then we extract the actionCommand String from this model:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class MyMcve extends JPanel {
private static final String[] SHAPES = {
"Circle", "Square", "Triangle"
};
private static final String[] COLORS = {
"Red", "Orange", "Yellow", "Green", "Blue"
};
private ButtonGroup shapeButtonGroup = new ButtonGroup();
private ButtonGroup colorButtonGroup = new ButtonGroup();
public MyMcve() {
JPanel shapesBtnPanel = new JPanel(new GridLayout(0, 1));
shapesBtnPanel.setBorder(BorderFactory.createTitledBorder("Shapes"));
for (String shape : SHAPES) {
JRadioButton radioButton = new JRadioButton(shape);
radioButton.setActionCommand(shape);
shapeButtonGroup.add(radioButton);
shapesBtnPanel.add(radioButton);
}
JPanel colorsBtnPanel = new JPanel(new GridLayout(0, 1));
colorsBtnPanel.setBorder(BorderFactory.createTitledBorder("Colors"));
for (String color : COLORS) {
JRadioButton radioButton = new JRadioButton(color);
radioButton.setActionCommand(color);
colorButtonGroup.add(radioButton);
colorsBtnPanel.add(radioButton);
}
JPanel bothButtonPanel = new JPanel(new GridLayout(1, 2));
bothButtonPanel.add(shapesBtnPanel);
bothButtonPanel.add(colorsBtnPanel);
JButton getSelectionBtn = new JButton(new GetSelectionAction("Get Selection"));
JPanel btnPanel = new JPanel();
btnPanel.add(getSelectionBtn);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout());
add(bothButtonPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}
private class GetSelectionAction extends AbstractAction {
public GetSelectionAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
String shapeSelection = "";
String colorSelection = "";
ButtonModel shapeModel = shapeButtonGroup.getSelection();
if (shapeModel != null) {
shapeSelection = shapeModel.getActionCommand();
}
ButtonModel colorModel = colorButtonGroup.getSelection();
if (colorModel != null) {
colorSelection = colorModel.getActionCommand();
}
System.out.println("Selected Shape: " + shapeSelection);
System.out.println("Selected Color: " + colorSelection);
}
}
private static void createAndShowGui() {
MyMcve mainPanel = new MyMcve();
JFrame frame = new JFrame("MCVE");
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(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
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.