JButtons,ActionListener和JOptionPane

时间:2014-10-16 20:24:28

标签: java swing jbutton actionlistener joptionpane

如果勾选或未勾选所需的项目但我没有得到任何内容,我正在尝试给出一个弹出式JOptionPane MessageDialog。基本上我正在检查使用动作侦听器按下哪个按钮,然后检查在上一个窗口中选择了哪个用户。如果不允许用户,那么它应该显示一个弹出消息对话框告诉他们,否则它应该检查是否在JCheckBox中勾选了所需的项目,如果勾选了正确的项目,它应该显示一个消息对话框“欢迎”他们进入室。

这些课程是在很久以前制作的,我知道我应该更好地命名它们以及我的变量。这是一个相当古老的项目,我从来没有完成,所以我编程的方式有很多缺陷,所以请不要打电话给我,虽然我们欢迎提示。

即使我说这是一个古老的项目,我仍然不擅长Java而且我还在学习,所以我的代码显然并不完美。

有些名字和信息都在南非荷兰语中,所以如果你有什么不明白的地方请问,我会为你改变它。

我无法弄清楚如何使用网站的代码突出显示,我希望我做得对,抱歉。

主要课程:

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

}
}

第一个窗口类:

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);
                    }
                }
         }
     );

}

}

第二个窗口类:

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");
            }
        }
    }
}
}

提前感谢任何解决/解决方案的尝试。

1 个答案:

答案 0 :(得分:3)

关于此代码:

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

出于调试目的,我已改为:

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

您会看到loggedU始终返回 0

你的问题是一个常见的新手错误 - 你正在创建一个新的window1对象,w02,并假设它的状态与之前创建的window1对象相同,而这不是Java的工作方式。要获取原始window1对象的状态,您需要对其进行测试,而不是新的不同实例。


如,

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();
            }
         }
      }
   }
}

修改
您的代码未考虑字符串大小写!

变化:

if (event.getActionCommand().equals(garage)) {

为:

if (event.getActionCommand().equalsIgnoreCase(garage)) {