简体   繁体   中英

JButtons, ActionListener, and JOptionPane

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.


eg,

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)) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM