JButtons, ActionListener, and JOptionPane - java

I'm trying to give a popup JOptionPane MessageDialog if the required items are ticked or not ticked but I don't get anything. Basically I'm checking which button is pressed using the action listener and then check which user was selected in the previous window. If the user is not allowed then it should show a popup message dialog telling them so, otherwise it should check whether the required items are ticked in the JCheckBox and if the correct items are ticked it should show a message dialog "welcoming" them into the room.
The classes were made quite a while ago and I know that I should be better in naming them as well as my variables. This is quite an old project that I never finished so there are many flaws in the way I programmed, so please don't call me out on that, although tips are welcome.
Even though I say this is an old project I am still not great at Java and I'm still learning so my code is not perfect, obviously.
Some of the names and messages are in Afrikaans so if there's anything you don't understand just ask and I'll change it for you.
I couldn't quite figure out how to use the site's code highlighting, I hope I did it right, sorry.
Main class:
import javax.swing.JFrame;
public class main {
public static void main(String args[]){
window1 w1Ob = new window1();
w1Ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w1Ob.setSize(250,250);
w1Ob.setVisible(true);
w1Ob.setLocationRelativeTo(null);
w1Ob.setResizable(true);
}
}
First window class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
//has to extend JFrame to use content from JFrame, cannot import to here but can to main class, not sure how it
//works
public class window1 extends JFrame{
//creating window2 object to run window2 if inserted password is correct
window2 wO2 = new window2();
//adds needed variables
//adds jlist which is the used list
private JList list;
//names used in the jlist, jlist uses string array
private static String[] usernames = {"Jannie", "Heloise", "Juan", "Chane"};
//font used to make text larger
Font font = new Font("Sans-Serif", Font.BOLD, 24);
//attempt at making a password array that stores all the passwords as strings then is used in an if statement
//to check if correct
private static int[] passwords = {1, 2, 3, 4};
//creating variable to know which user is logged in
public int loggedUser;
//constructor to create the window
public window1(){
//title
super("Project");
//the layout used, FlowLayout, most basic layout as temporary solution until learning new one
setLayout(new FlowLayout());
//tells the jlist to use the usernames string array to display in the list, meaning it will display
//Jannie on list 1, Heloise on line 2, etc.
list = new JList(usernames);
//tells the jlist how many lines to display, if array contains > 4 strings and is told to display only
//4 it will give a scroll bar
list.setVisibleRowCount(4);
//makes sure only 1 item in the list is selected
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//sets the jlist lists' font to preset font in variable at the top of the class
list.setFont(font);
//adds the jlist to the screen
add(new JScrollPane(list));
//adds the listener to wait for the user to select an item in the list, thus "ListSelection"
list.addListSelectionListener(
//anonymous class insides parameters for adding the listener to list
new ListSelectionListener(){
//obligatory overwrite, parameters of "ListSelectionEvent event" obligatory, not sure what
//it does...
public void valueChanged(ListSelectionEvent event){
//creating the OptionPane for the password
String pass = JOptionPane.showInputDialog(null, "Enter Password");
//converts pass to string under variable name i
int i = Integer.parseInt(pass);
//checks if entered value is equal to the value in the array, example, Jannie = list[0]
//because it's the first value in array list and 1 = pass[0] since it's the first value
//in array passwords, thus if 1 is entered it will be correct because it's the
//corresponding value in the arrays
if(i == passwords[list.getSelectedIndex()]){
int selectedValue = list.getSelectedIndex();
if(selectedValue == 0){
loggedUser = 1;
}
else if(selectedValue == 1){
loggedUser = 2;
}
else if(selectedValue == 2){
loggedUser = 3;
}
else if(selectedValue == 3){
loggedUser = 4;
}
wO2.setDefaultCloseOperation(EXIT_ON_CLOSE);
wO2.setSize(500, 500);
wO2.setVisible(true);
wO2.setLocationRelativeTo(null);
wO2.setResizable(true);
}
}
}
);
}
}
Second window class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class window2 extends JFrame{
//adding JButton variables for each button on the screen
private JButton garage;
private JButton kombuis;
private JButton badkamer;
private JButton mancave;
//adding JCheckBox variables for each required item
public JCheckBox sleutel;
public JCheckBox helmet;
public JCheckBox voorskoot;
public JCheckBox beker;
public JCheckBox handdoek;
public JCheckBox seep;
public JCheckBox musiek;
//adding String variable to tell the user what he requires to enter the area he wants
private String youNeed;
private JButton button;
public window2(){
//title
super("Access");
//3 rows (int), 4 columns (int), 15 px horizontal gap (int), 15 px vertical gap (int)
setLayout(new GridLayout(3, 4, 2, 5));
//gives parameters for garage, puts text "Garage" on the button
garage = new JButton("Garage");
//adds garage JButton to the screen
add(garage);
//gives parameters for kombuis, puts text "Kombuis" on the button
kombuis = new JButton("Kombuis");
//adds kombuis JButton to the screen
add(kombuis);
//gives parameters for badkamer, puts text "Badkamer" on the button
badkamer = new JButton("Badkamer");
//adds badkamer JButton to the screen
add(badkamer);
//gives parameters for mancave, puts text "Mancave" on the button
mancave = new JButton("Mancave");
//adds mancave JButton to the screen
add(mancave);
sleutel = new JCheckBox("Sleutel");
add(sleutel);
helmet = new JCheckBox("Helmet");
add(helmet);
voorskoot = new JCheckBox("Voorskoot");
add(voorskoot);
beker = new JCheckBox("Beker");
add(beker);
handdoek = new JCheckBox("Handdoek");
add(handdoek);
seep = new JCheckBox("Seep");
add(seep);
musiek = new JCheckBox("Musiek");
add(musiek);
HandlerClass handler = new HandlerClass();
//adds action listeners for following button to wait for user to select one
garage.addActionListener(handler);
kombuis.addActionListener(handler);
badkamer.addActionListener(handler);
mancave.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
//create window1 object to use loggedUser variable from window1
window1 wo1 = new window1();
//create variable using window1 object to use loggedUser variable in window2 class
int loggedU = wo1.loggedUser;
if(event.getActionCommand().equals(garage)){
if(loggedU == 1){
if(sleutel.isSelected() && helmet.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the garage, Jannie");
}
else{
if(sleutel.isSelected()){
youNeed = "Helmet";
}
else if(helmet.isSelected()){
youNeed = "Sleutel";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else if(loggedU == 3){
if(sleutel.isSelected() && helmet.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the garage, Juan");
}
else{
if(sleutel.isSelected()){
youNeed = "Helmet";
}
else if(helmet.isSelected()){
youNeed = "Sleutel";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else{
JOptionPane.showMessageDialog(null, "You're not allowed in here");
}
}
if(event.getActionCommand().equals(badkamer)){
if(loggedU == 1){
if(handdoek.isSelected() && seep.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the bathroom, Jannie");
}
else{
if(handdoek.isSelected()){
youNeed = "Seep";
}
else if(seep.isSelected()){
youNeed = "Handdoek";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else if(loggedU == 2){
if(handdoek.isSelected() && seep.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the bathroom, Heloise");
}
else{
if(handdoek.isSelected()){
youNeed = "Seep";
}
else if(seep.isSelected()){
youNeed = "Handdoek";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else if(loggedU == 3){
if(handdoek.isSelected() && seep.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the bathroom, Juan");
}
else{
if(handdoek.isSelected()){
youNeed = "Seep";
}
else if(seep.isSelected()){
youNeed = "Handdoek";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else if(loggedU == 4){
if(handdoek.isSelected() && seep.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the bathroom, Chane");
}
else{
if(handdoek.isSelected()){
youNeed = "Seep";
}
else if(seep.isSelected()){
youNeed = "Handdoek";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
}
if(event.getActionCommand().equals(kombuis)){
if(loggedU == 2){
if(voorskoot.isSelected() && beker.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the kombuis, Heloise");
}
else{
if(voorskoot.isSelected()){
youNeed = "beker";
}
else if(beker.isSelected()){
youNeed = "voorskoot";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else if(loggedU == 4){
if(voorskoot.isSelected() && beker.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the kombuis, Chane");
}
else{
if(voorskoot.isSelected()){
youNeed = "beker";
}
else if(beker.isSelected()){
youNeed = "voorskoot";
}
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else{
JOptionPane.showMessageDialog(null, "You're not allowed in here");
}
}
if(event.getActionCommand().equals(mancave)){
if(loggedU == 1){
if(musiek.isSelected()){
JOptionPane.showMessageDialog(null, "Welcome to the mancave, Jannie");
}
else{
youNeed = "musiek";
JOptionPane.showMessageDialog(null, "You do not have the required items, you need: " + youNeed);
}
}
else{
JOptionPane.showMessageDialog(null, "You're not allowed in here");
}
}
}
}
}
Thanks in advance for any attempts at solving/solutions.

Regarding this code:
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
window1 wo1 = new window1(); // ***** problem is here *****
int loggedU = wo1.loggedUser;
if (event.getActionCommand().equals(garage)) {
which for debugging purposes, I've changed to:
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
window1 wo1 = new window1(); // ***** problem is here *****
int loggedU = wo1.loggedUser;
System.out.println("action command: " + event.getActionCommand()); //!!
System.out.println("loggedU: " + loggedU);
if (event.getActionCommand().equals(garage)) {
You'll see that loggedU always returns 0.
Your problem is a common newbie mistake -- you are creating a new window1 object, w02, and are assuming that its state is the same as a previously created window1 object, and that's not how Java works. To get the state of the original window1 object, you will need to test it, and not a new and different instance.
e.g.,
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.Window;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class MyTest {
private static void createAndShowGui() {
MainGuiPanel mainGuiPanel = new MainGuiPanel();
final JFrame frame = new JFrame("MyTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainGuiPanel);
frame.pack();
frame.setLocationRelativeTo(null);
// frame.setVisible(true);
DialogPanel dialogPanel = new DialogPanel();
JDialog dialog = new JDialog(frame, "Select User", ModalityType.APPLICATION_MODAL);
dialog.add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
// show modal dialog
dialog.setVisible(true);
// here dialog is no longer visible
// extract datat from dialog's dialogPanel
String selectedUser = dialogPanel.getSelectedName();
// put into the main GUI
mainGuiPanel.setSelectedUser(selectedUser);
// now show the main GUI's JFrame
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MainGuiPanel extends JPanel {
private static final long serialVersionUID = 1L;
private JButton doItButton = new JButton(new DoItAction("Do It!", KeyEvent.VK_D));
private String selectedUser;
public MainGuiPanel() {
add(doItButton);
}
public void setSelectedUser(String selectedUser) {
this.selectedUser = selectedUser;
}
private class DoItAction extends AbstractAction {
public DoItAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Selected User: " + selectedUser);
}
}
}
class DialogPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static final String[] USER_NAMES = { "Jannie", "Heloise", "Juan", "Chane" };
private JList<String> userList = new JList<>(USER_NAMES);
private String selectedName;
public DialogPanel() {
userList.addListSelectionListener(new UserListListener());
add(new JScrollPane(userList));
}
public String getSelectedName() {
return selectedName;
}
private class UserListListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
selectedName = userList.getSelectedValue();
if (selectedName != null) {
Window win = SwingUtilities.getWindowAncestor(DialogPanel.this);
win.dispose();
}
}
}
}
}
Edit
Your code is not taking String capitalization into account!
Change:
if (event.getActionCommand().equals(garage)) {
to:
if (event.getActionCommand().equalsIgnoreCase(garage)) {

Related

Trying to figure out how to error handler into this candy machine program

Got this program for a candy machine GUI finished, but I can't figure out where to put in the InputMismatchException code. I've tried putting it in under the input for entering the payments, but I can't find a way to put it in the right area, I don't know what I'm doing wrong.
Main Candy Machine Class
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import java.util.InputMismatchException;
public class candyMachine extends JFrame {
//window size setup
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
//setup for the store items and register
private CashRegister cashRegister = new CashRegister();
private Dispenser candy = new Dispenser(100, 50);
private Dispenser chips = new Dispenser(100, 65);
private Dispenser gum = new Dispenser(75, 45);
private Dispenser cookies = new Dispenser(100, 85);
//heading and button setups
private JLabel headingMainL;
private JLabel selectionL;
private JButton exitB, candyB, chipsB, gumB, cookiesB;
private ButtonHandler pbHandler;
//the main machine constructor
public candyMachine() {
setTitle("Candy Machine"); // window title
setSize(WIDTH, HEIGHT); // window size
Container pane = getContentPane(); //container get
pane.setLayout(new GridLayout(7,1)); //pane layout setup
pbHandler = new ButtonHandler(); //instantiate listener object
//Store sign setup
headingMainL = new JLabel("WELCOME TO SHELLY'S CANDY SHOP", SwingConstants.CENTER);
//instructions setup
selectionL = new JLabel("To Make a Selection, " + "Click on the Product Button", SwingConstants.CENTER);
//adding the labels to the panes
pane.add(headingMainL);
pane.add(selectionL);
//candy button setup
candyB = new JButton("Candy");
//registering the listener for the candy button
candyB.addActionListener(pbHandler);
//chip button setup
chipsB = new JButton("Chips");
//Registering listener for chips button
chipsB.addActionListener(pbHandler);
//gum button setup
gumB = new JButton("Gum");
//registering the listener for the gum button
gumB.addActionListener(pbHandler);
//cookie button setup
cookiesB = new JButton("Cookies");
//registering the listener for the cookie button
cookiesB.addActionListener(pbHandler);
//exit button setup
exitB = new JButton("Exit");
//registering the listener for the exit button
exitB.addActionListener(pbHandler);
pane.add(candyB); //adds the candy button to the pane
pane.add(chipsB); //adds the chips button to the pane
pane.add(gumB); //adds the gum button to the pane
pane.add(cookiesB); //adds the cookies button to the pane
pane.add(exitB); //adds the exit button to the pane
setVisible(true); //show the window and its contents
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//class to handle button events
private class ButtonHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getActionCommand().equals("Exit"))
System.exit(0);
else if (e.getActionCommand().equals("Candy"))
sellProduct(candy, "Candy");
else if (e.getActionCommand().equals("Chips"))
sellProduct(chips, "Chips");
else if (e.getActionCommand().equals("Gum"))
sellProduct(gum, "Gum");
else if (e.getActionCommand().equals("Cookies"))
sellProduct(cookies, "Cookies");
}
}
//Method to sell machine items
private void sellProduct(Dispenser product, String productName) {
//int variables for the amount of money entered, prices, and money needed
int coinsInserted = 0;
int price;
int coinsRequired;
String str;
// if statement for buying the products
if (product.getCount() > 0) {
price = product.getProductCost();
coinsRequired = price - coinsInserted;
while (coinsRequired > 0) {
str = JOptionPane.showInputDialog("To buy " + productName + " please insert " + coinsRequired + " cents");
coinsInserted = coinsInserted
+ Integer.parseInt(str);
coinsRequired = price - coinsInserted;
}
cashRegister.acceptAmount(coinsInserted);
product.makeSale();
JOptionPane.showMessageDialog(null, "Please pick up " + "your " + productName + " and enjoy",
"Thank you, Come again!", JOptionPane.PLAIN_MESSAGE);
} else //if that item is sold out
JOptionPane.showMessageDialog(null, "Sorry " + productName + " is sold out\n" + "Please make another selection",
"Thank you, Come again!", JOptionPane.PLAIN_MESSAGE);
}
public static void main(String[] args) {
candyMachine candyShop = new candyMachine();
}
}
Cash Register Class
public class CashRegister {
private int regiCash; //int variable for storing cash in the "register"
public CashRegister()
{ // default amount of cash on hand is 500
regiCash = 500;
}
//Method that receives the cash entered by the user and updates the register
public void acceptAmount(int amountIn) {
regiCash = regiCash + amountIn;
}
//Constructer for setting the amount of money in the register to a specific amount (500)
public CashRegister(int cashIn)
{
if (cashIn >= 0)
regiCash = cashIn;
else
regiCash = 500;
}
//Method to show the current amount of money in the cash register
public int currentBalance()
{
return regiCash;
}
}
Dispenser Class
public class Dispenser {
private int itemNumber; //int variable for storing the number of items in the dispenser
private int price; //int variable for storing item prices
//item constructor
public Dispenser(int i, int j)
{ //default number of items is 5 and default price is 50
itemNumber = 5;
price = 50;
}
public int getCount()
{
return itemNumber;
}
public void makeSale()
{
itemNumber--;
}
public int getProductCost()
{
return price;
}
}
Button Handler Class
package lab9Final;
public class ButtonHandler {
//Handles the buttons
}

How do I use the outcome of my actionPerformed method to effect the main method - java

I have a class called Screen containing the actionPerformed method.
I want a different outcome for the different menu items: random, aggressive and human.
This outcome effects the main method, however I am unsure how to link the two...
public class Screen extends JFrame
implements ActionListener {
ActionListener listener;
JMenuItem random = new JMenuItem("Random");
JMenuItem aggressive = new JMenuItem("Aggressive");
JMenuItem human = new JMenuItem("Human");
public Screen(Board board){
//menuBar items
menu.add(random);
random.addActionListener(this);
menu.add(aggressive);
aggressive.addActionListener(this);
menu.add(human);
human.addActionListener(this);
....
//sets up board of buttons and adds actionListener to each.
....
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == random){
}
if(e.getSource() == aggressive){
}
if(e.getSource() == human){
}
//code for the board buttons - nothing to do with the menu.
//But thought it might help
if (numClicks == 0){
JButton piece = (JButton) e.getSource();
String xy = piece.getName();
String x = xy.substring(0,1);
String y = xy.substring(2,3);
FromXInt = Integer.parseInt(x);
FromYInt = Integer.parseInt(y);
System.out.println("From" + " " +FromXInt + "," + FromYInt);
}
else{
JButton piece = (JButton) e.getSource();
String xy = piece.getName();
String x = xy.substring(0,1);
String y = xy.substring(2,3);
ToXInt = Integer.parseInt(x);
ToYInt = Integer.parseInt(y);
System.out.println("To" + " " + ToXInt + "," + ToYInt);
}
numClicks++;
if (numClicks >= 2){
numClicks = 0;
}
return;
}
}
My class which contains the main method:
public class Chess{
public static void main(String [ ] args){
Screen s = new Screen(board);
// my attempt but doesn't work
if (s.actionPerformed(e) == random){
.....
note: I am new to Java and still trying to get my head round the linking of multiple classes.
--------------------The ActionPerformed method also contains events if buttons are clicked but I haven't added that code in because it over complicates things.--
This approach uses a public enum and sets the style variable according to the users menu choice:
package chess;
//...
public class Screen extends JFrame
implements ActionListener {
private JMenuItem random = new JMenuItem("Random");
private JMenuItem aggressive = new JMenuItem("Aggressive");
private JMenuItem human = new JMenuItem("Human");
public enum PlayStyle {Random, Aggressive, Human};
private PlayStyle style;
public Screen(Board board) {
//menuBar items
menu.add(random);
random.addActionListener(this);
menu.add(aggressive);
aggressive.addActionListener(this);
menu.add(human);
human.addActionListener(this);
//....
//sets up board of buttons and adds actionListener to each.
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == random) {
style=PlayStyle.Random;
}
if (e.getSource() == aggressive) {
style=PlayStyle.Aggressive;
}
if (e.getSource() == human) {
style=PlayStyle.Human;
}
//code for the board buttons - nothing to do with the menu.
//....
}
public PlayStyle getStyle(){
return style;
}
}
This is the class that contains the main method:
package chess;
import chess.Screen.PlayStyle;
public class Chess{
public static void main(String [ ] args){
Screen s = new Screen(board);
// this attempt will work
if (s.getStyle()==PlayStyle.Random) {
...
} else if (s.getStyle()==PlayStyle.Aggressive){
...
You are calling a method and it seems that you want to use something that comes back from that method but the method itself returns nothing, i.e. "void". I changed your Screen class so that the method returns something now.
public class Screen extends JFrame
implements ActionListener {
public Source actionPerformed(ActionEvent e) {
....
if(e.getSource() == random){
}
if(e.getSource() == aggressive){
}
if(e.getSource() == human){
}
return e.getSource()
}
The main method will now be able to receive a result from the call and use it.

GUI with 3 Jbuttons, and a list that stores the selected buttons/list parameters and can display them separately

I want to make a GUI where I have a list where one item can be selected, 3 JButtons, ON, OFF and STATE. When the Jbutton "State" is selected a separate box pops up telling the user if they selected ON / OFF and which parameter they selected from the JList. This is my code so far. The pop up box keeps telling me that the heater is on, because it keeps reading on = true. Also, the part where I try to select off the list is completely wrong aswel for some reason I can't see.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Heater extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private Object state;
private boolean on;
private Object inten;
//private JList HeatIntensity;
private String intensity[] = {"Level 1", "Level 2", "Level 3", "Level 4", "Level 5"};
public Heater() {
super("Heater");
//creating box
box(intensity);
}
public static void main(String[] args){
new Heater();
}
#Override
public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();
//if on button is pressed, on = true
if (action.equals("ON")) {
on = true;
}
//if off pressed on = false
else if (action.equals("OFF")) {
on = false;
}
if (action.equals("State")) {
//if the on/off button was pressed then the state button, a new box pops up telling if on / off
if(on = true){
JOptionPane.showMessageDialog(null, "on");
}
else if(on = false)
JOptionPane.showMessageDialog(null, "The Heawdadwqwdqwdater is off");
}
//when somthing is pressed on the list, show that in a new pop up box
/*intensity.additemListener(
new itemlistener(){
public void itemChanged(ItemEvent event){
if(event.getStateChange() == ItemEvent.SELECTED){
JOptionPane.showMessageDialog(null, ItemEvent.SELECTED);
}
}
}
);
*/
}
public void box(String[] a){
//creating the box
this.getContentPane().setLayout(new FlowLayout());
setSize(new Dimension(900, 300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
//creating Jbuttons
JButton buttonon = new JButton("ON");
JButton buttonoff = new JButton("OFF");
JButton buttonState = new JButton("State");
//creating list
JList list = new JList(a);
list.setVisibleRowCount(5);
add(list);
//adding buttons
add(buttonon);
add(buttonoff);
add(buttonState);
buttonon.addActionListener(this);
buttonoff.addActionListener(this);
buttonState.addActionListener(this);
setVisible(true);
}
}
The problem is this chunk of code:
if(on = true){
JOptionPane.showMessageDialog(null, "on");
}
else if(on = false)
JOptionPane.showMessageDialog(null, "The Heawdadwqwdqwdater is off");
Doing if (on = true) assigns true to on instead of checking if it is true. That means that the code in the block will always be executed. The same applies for the else if, although it will never reach it.
The correct way to do this is
if (on) {
JOptionPane.showMessageDialog(null, "on");
}
else {
JOptionPane.showMessageDialog(null, "The Heawdadwqwdqwdater is off");
}

Java Swing Timer Not Clear

I have been having some problems with using the Timer function of Java swing. I am fairly new to programming with Java, so any help is greatly appreciated. I have looked over many other Timer questions on this site but none of them have answered my question. I have made a GUI that allows you to play rock paper scissors, where you can choose from clicking three buttons. I want my program to sleep for around 1 second after you click the button, and again after it displays a message. After I realized Thread.sleep() wouldn't work for my GUI, I tried to implement a timer.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import java.io.*;
public class rps {
//ROCK PAPER SCISSORS
static JLabel middle = new JLabel();
static JLabel them = new JLabel();
static JLabel yourWins = new JLabel();
static JLabel theirWins = new JLabel();
static JPanel yourPanel = new JPanel();
static JPanel middlePanel = new JPanel();
static JLabel blank1 = new JLabel();
static JLabel blank2 = new JLabel();
static JButton rock = new JButton("Rock");
static JButton paper = new JButton("Paper");
static JButton scissors = new JButton("Scissors");
static int yw = 0;
static int tw = 0;
static ButtonHandler listener = new ButtonHandler();
public static void main(String[] args) {
//Create the frame
JFrame frame = new JFrame("Rock Paper Scissors");
frame.setSize(500, 500); //Setting the size of the frame
middle.setFont(new Font("Serif", Font.PLAIN, 30));
middle.setHorizontalAlignment(SwingConstants.CENTER);
them.setFont(new Font("Serif", Font.PLAIN, 15));
them.setHorizontalAlignment(SwingConstants.CENTER);
yourWins.setHorizontalAlignment(SwingConstants.CENTER);
theirWins.setHorizontalAlignment(SwingConstants.CENTER);
//Creating panels
JPanel bigPanel = new JPanel();
Border border = BorderFactory.createLineBorder(Color.BLACK, 1);
Border wlb = BorderFactory.createLineBorder(Color.RED, 1);
them.setBorder(border);
yourPanel.setBorder(border);
bigPanel.setBorder(border);
yourWins.setBorder(wlb);
theirWins.setBorder(wlb);
middlePanel.setBorder(border);
//Creating grid layouts
GridLayout yourGrid = new GridLayout(1,3,10,10);
GridLayout theirGrid = new GridLayout(1,1); //One row, one column
GridLayout middleGrid = new GridLayout(5,1);
GridLayout bigGrid = new GridLayout(3,1);//Two rows, one column
//Setting the layouts of each panel to the grid layouts created above
yourPanel.setLayout(yourGrid); //Adding layout to buttons panel
them.setLayout(theirGrid); //Adding layout to label panel
middlePanel.setLayout(middleGrid);
bigPanel.setLayout(bigGrid);
//Adding r/p/s to your grid.
yourPanel.add(rock);
yourPanel.add(paper);
yourPanel.add(scissors);
//Adding w/l rations to middlegrid.
middlePanel.add(theirWins);
middlePanel.add(blank1);
middlePanel.add(middle);
middlePanel.add(blank2);
middlePanel.add(yourWins);
//Attaching the listener to all the buttons
rock.addActionListener(listener);
paper.addActionListener(listener);
scissors.addActionListener(listener);
bigPanel.add(them);
bigPanel.add(middlePanel);
bigPanel.add(yourPanel);
//Shows the score at 0-0.
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
frame.getContentPane().add(bigPanel); //panel to frame
frame.setVisible(true); // Shows frame on screen
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//Class represents what do when a button is pressed
private static class ButtonHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
Timer timer = new Timer(1000, this);
String tc = random();
them.setText("They chose: " + tc + "!");
if (e.getSource() == rock) {
whoWins("rock", tc);
} else if (e.getSource() == paper) {
whoWins("paper", tc);
} else if (e.getSource() == scissors) {
whoWins("scissors", tc);
}
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
timer.setRepeats(false);
timer.start();
}
}
public static String random() {
int random = (int) (Math.random() * 3);
if (random == 0) {
return "Rock";
} else if (random == 1) {
return "Paper";
} else if (random == 2) {
return "Scissors";
}
return "";
}
public static void whoWins(String yc, String tc) {
if (yc.equals("rock")) {
if (tc.equals("Rock")) {
middle.setText("It's a tie!");
} else if (tc.equals("Paper")) {
middle.setText("You lose!");
tw++;
} else if (tc.equals("Scissors")) {
middle.setText("You win!");
yw++;
}
} else if (yc.equals("paper")) {
if (tc.equals("Rock")) {
middle.setText("You win!");
yw++;
} else if (tc.equals("Paper")) {
middle.setText("It's a tie!");
} else if (tc.equals("Scissors")) {
middle.setText("You lose!");
tw++;
}
} else if (yc.equals("scissors")) {
if (tc.equals("Rock")) {
middle.setText("You lose!");
tw++;
} else if (tc.equals("Paper")) {
middle.setText("You win!");
yw++;
} else if (tc.equals("Scissors")) {
middle.setText("It's a tie!");
}
}
}
}
What is actually happening is there is no delay from when I press the button to a message displaying, because clearly I am not using the timer correctly. I would like the timer to just run once, and after it runs the code will execute. However, when I click a button the timer will run on repeat although setRepeats is false. Therefore, the message I want to display, instead of being delayed, is displayed instantaneously but then goes on a loop and keeps displaying a message (the message is random) until I shut off the program. If I click the button again, it will double the tempo of the timer it seems, and the messages display twice as fast and so on and so forth.
them.setText("They chose: " + tc + "!");
This is the message that is displayed on repeat, with the variable tc changing every time. The timer seems to just be displaying this message every timer interval (1s).
Any help would be greatly appreciated.
EDIT:
So I added this section :
private static class ButtonHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
// I'd be disabling the buttons here to prevent
// the user from trying to trigger another
// update...
// This is an instance field which is used by your
// listener
Timer timer = new Timer(1000, listenert);
timer.setRepeats(false);
timer.start();
}
}
private static class timer implements ActionListener {
public void actionPerformed (ActionEvent e) {
String tc = random(); //A method that chooses a random word.
them.setText("They chose: " + tc + "!");
if (e.getSource() == rock) {
whoWins("rock", tc); //whoWins is a method that will display a message.
} else if (e.getSource() == paper) {
whoWins("paper", tc);
} else if (e.getSource() == scissors) {
whoWins("scissors", tc);
}
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
// Start another Timer here that waits 1 second
// and re-enables the other buttons...
}
}
so what I believe happens now is when I click a button, the buttonhandler listener starts the timer which is attached to the timer listener (named listenert) which will run the code in the actionPerformed of the timer class. however the sleep function still is not working
EDIT 2.5:
private static class ButtonHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
final JButton button = (JButton)e.getSource();
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
String tc = random();
them.setText("They chose: " + tc + "!");
if (button == rock) {
whoWins("rock", tc);
} else if (button == paper) {
whoWins("paper", tc);
} else if (button == scissors) {
whoWins("scissors", tc);
}
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
}
});
timer.setRepeats(false);
timer.start();
}
}
that is what I have so far, I just need to add antoher sleep after
them.setText("They chose: " + tc + "!");
where would I put a timer.restart() if any? the timer.start() is at the end of the method which I don't quite understand.
So, the ActionListener you supply to the Timer is notified when the timer "ticks", so you ButtonHandler actionPerformed should look more like...
public void actionPerformed (ActionEvent e) {
// I'd be disabling the buttons here to prevent
// the user from trying to trigger another
// update...
// This is an instance field which is used by your
// listener
choice = e.getSource();
Timer timer = new Timer(1000, listener);
timer.setRepeats(false);
timer.start();
}
And your listener should look more like
public void actionPerformed (ActionEvent e) {
String tc = random(); //A method that chooses a random word.
them.setText("They chose: " + tc + "!");
if (choice == rock) {
whoWins("rock", tc); //whoWins is a method that will display a message.
} else if (choice == paper) {
whoWins("paper", tc);
} else if (choice == scissors) {
whoWins("scissors", tc);
}
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
// Start another Timer here that waits 1 second
// and re-enables the other buttons...
}
For example...
You may consider taking a look at How to use Swing Timers for more details
Updated
Start with a simple example...
public class TestPane extends JPanel {
private JLabel label;
private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
public TestPane() {
setLayout(new GridBagLayout());
label = new JLabel();
add(label);
tick();
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tick();
}
});
timer.start();
}
protected void tick() {
label.setText(sdf.format(new Date()));
}
}
This just calls the tick method every half second to update the time on the JLabel...
firstly import the following ;
import java.awt.event.ActionEvent ;
import java.awt.event.ActionListener ;
import javax.swing.Timer ;
then initialize the timer at the end of the form like this ;
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new mainprogramme().setVisible(true);
}
});
}
private Timer timer ;
then after initializing the timer add a public class like following;
public class progress implements ActionListener {
public void actionPerformed(ActionEvent evt){
int n = 0 ;
if (n<100){
n++ ;
System.out.println(n) ;
}else{
timer.stop() ;
}
}
}
after you do this go to the j Frame>right click and select>Events>window>window Opened and type the following ;
private void formWindowOpened(java.awt.event.WindowEvent evt) {
timer = new Timer(100,new progress()) ;
and after you do all this take a button name it as anything and type the following in its void like following ;
timer.start();
AND THAT'S IT CODE IT AND THEN REPLY ME...

Item Listeners Error

I'm having an issue with Item Listeners.It's the first time I'm using it, so far all I've used is the Item Event. I was wondering if you could clear up what the difference between those two, as well point me out what I'm doing wrong.
My issue is on line 46 the line starting with: Object source = toppingList.getSource(); and the error I get is 'Cannot find symbol'.
I'm thinking I'm using the wrong item before the getSource();, I thought that the toppingList was the correct item, I can't see which other item I could put in it's place.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Pizza extends JFrame{
FlowLayout flow = new FlowLayout();
JComboBox pizzaBox = new JComboBox();
JLabel toppingList = new JLabel("Topping List");
JLabel aLabel = new JLabel("Paulos's American Pie");
JTextField totPrice = new JTextField(10);
int[] pizzaPrice = {7,10,10,8,8,8,8};
int totalPrice = 0;
String output;
int pizzaNum;
public Pizza()
{
super("Pizza List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
pizzaBox.addItemListener((ItemListener) this);
add(toppingList);
pizzaBox.addItem("cheese");
pizzaBox.addItem("sausage");
pizzaBox.addItem("pepperoni");
pizzaBox.addItem("onion");
pizzaBox.addItem("green pepper");
pizzaBox.addItem("green olive");
pizzaBox.addItem("black olive");
add(pizzaBox);
add(aLabel);
add(totPrice);
}
public static void main(String[] arguments)
{
JFrame frame = new DebugFourteen3();
frame.setSize(200, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent[] list)
{
Object source = toppingList.getSource();
if(source == pizzaBox)
{
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
Gui elements do not have any getSource, it is a method of the event - telling you which gui element generated the event. But you know what the source of the event is, since in your constructor you wrote:
pizzaBox.addItemListener((ItemListener) this);
and you did not add this to any other gui element. So you cannot get events from any other gui element. So do not test for it.
But there are other issues:
Your PizzaBox should implement ItemListener:
public class Pizza extends JFrame implement ItemListener
and then just write
pizzaBox.addItemListener(this);
If you want to listen to multiple elements, add separate anonymous listener for each (and Pizza does not implement ItemListener)
// in your constructor:
pizzaBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
pizzaNum = pizzaBox.getSelectedIndex(); // in your code you have int pizzaNum but at the same time, pizzaNum is a class variable, probably an error
// and so on
}
}
});
or you can move the code to a separate method
public class Pizza extends JFrame {
public Pizza() {
:
pizzaBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pizzaBox_itemStateChanged(e);
}
});
:
}
private void pizzaBox_itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
pizzaNum = pizzaBox.getSelectedIndex();
// and so on
}
}
:
}
You need to implement ItemListener with class. For details go through this tutorial
public class Pizza extends JFrame implements ItemListener{
.....
public Pizza(){
pizzaBox.addItemListener(this);// Here this is enough
....
}
// itemStateChanged should write as follows
public void itemStateChanged(ItemEvent e) {
//It will be enable if checkbox is selected
if (e.getStateChange() == ItemEvent.SELECTED) {
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}

Categories