java - JButtons、ActionListener 和 JOptionPane

标签 java swing jbutton actionlistener joptionpane

如果所需的项目被勾选或未被勾选,我试图提供一个弹出式 JOptionPane MessageDialog 但我没有得到任何东西。基本上,我使用 Action 监听器检查按下了哪个按钮,然后检查在上一个窗口中选择了哪个用户。如果不允许用户,那么它应该显示一个弹出消息对话框告诉他们,否则它应该检查是否在 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");
            }
        }
    }
}
}

在此先感谢您尝试解决/解决方案。

最佳答案

关于这段代码:

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

关于java - JButtons、ActionListener 和 JOptionPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26413260/

相关文章:

java - 在 java swing 应用程序中使用线程设置/刷新信息的好方法

java - 网格布局不按约束调整大小

java - 释放按钮后执行操作

java - 从字符串中提取标记

java - java 程序中总计未正确打印并显示零

java - 如何确定一个类是否不可变

java - 如何在 JTabbedPane 中删除 "tab borders"

java - 如何更改 "panel.add(new JLabel(""));"中 JLabel 的字体大小

java - 如何根据我的棋盘格调整图像图标的大小?

java - AS3Crypto 和 Javax.Crypto 之间的加密/解密 ECB/PKS5/Blowfish 失败并出现填充错误