簡體   English   中英

如何在關鍵監聽器的 scope 之外使用 boolean

[英]How to use a boolean outside the scope of a key listener

我創建了一個購物車登錄 JFrame 並添加了一個“shopkeeperToggle”,這樣當按下它時,用戶登錄到店主的 JFrame,否則登錄到購物者的 Z3AD02CFB81F6B63ADZBE478 問題是我不知道如何實現它,我嘗試將 boolean 設置為 false 每當在“shopkeeperToggle”鍵監聽器中釋放鍵時,顯然我無法使用按下的值 inside登錄按鈕。

這是切換的代碼:

    shopkeeperToggle = new JToggleButton("Shopkeeper");
    shopkeeperToggle.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            pressed = false;
        }
    });

這就是我在登錄按鈕中嘗試做的事情:

signinButton = new JButton("Sign in ");
    signinButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
             try {
                        Class.forName("com.mysql.jdbc.Driver");
                        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3308/shoppingCart","root","");
                        // select the users that have the inputted credentials from the database
                        String sql = "SELECT * FROM users WHERE userUsername = ? AND userEmail =?AND userPassword = ? ";
                    PreparedStatement ps = conn.prepareStatement(sql);
                    ps.setString(1,usernamelogin.getText());
                    ps.setString(2, emaillogin.getText());
                    ps.setString(3,passwordlogin.getText());
                    ResultSet rs = ps.executeQuery();
                    // if query executed and 
                    if (rs.next()) {
                        // if login succ show window log succ, and go to home shopping page
                            JOptionPane.showMessageDialog(null,"Login successful! :)");
/////////////////this is where I fail////////////////////
                            if (pressed) {
                                OwnerHomePage ownerhome = new OwnerHomePage();
                                ownerhome.setVisible(true);
                                setVisible(false);
                            } else {
                                UserHomePage home = new UserHomePage();
                                home.setVisible(true);
                                setVisible(false);
                            }
                        } else {
                            JOptionPane.showMessageDialog(null,"Wrong Username or Email or Password :(");
                        }
                    } catch (Exception e1) {
                        JOptionPane.showMessageDialog(null,e1);
                    }
                }
            }

這可能會為解決您的問題提供一些幫助。 這是一個完全可編譯的演示。 進行了以下更改。

  • 使用Actions代替KeyListener 設置涉及更多一點,但可以將它們配置為僅監視某些鍵。
  • 使用JButton代替JToggleButton 沒有具體原因,可以更改。
  • 為偵聽器創建單獨的內部類。 傾向於減少混亂並且通常更具可讀性。
  • 根據模式更改按鈕的名稱。
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractAction;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class ActionMapAndButtons {

    JFrame frame = new JFrame("Demo");

    public static void main(String[] args) {
        SwingUtilities
                .invokeLater(() -> new ActionMapAndButtons().start());
    }

    public void start() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        MyClass cls = new MyClass();
        frame.add(cls);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class MyClass extends JPanel {
    JButton button = new JButton("Shopper Sign in");
    boolean pause = false;

    public MyClass() {
        setPreferredSize(new Dimension(300, 300));
        button.addActionListener(new ButtonListener());
        add(button);
        InputMap map = getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        for (int i = 0; i < 256; i++) {
            map.put(KeyStroke.getKeyStroke((char)i), "anyKey");
        }
        getActionMap().put("anyKey", new MyAction());
        setFocusable(true);

    }

    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            Object obj = ae.getSource();
            if (obj instanceof JButton) {
                JButton b = (JButton) obj;
                pause = !pause;
                if (pause) {
                    b.setText("Shopkeeper Sign in");
                } else {
                    b.setText("Shopper Sign in");
                }
            }
        }
    }

    private class MyAction extends AbstractAction {
        public void actionPerformed(ActionEvent ae) {
            String cmd = ae.getActionCommand();
            if (pause) {
                System.out.println("Shopkeeper - " + cmd);
            } else {
                System.out.println("Shopper - " + cmd);
            }
        }
    }
}

Java 教程中介紹了Inner (或nested )類和action

您可以將按下定義為 static 值;

class c {
    static boolean pressed = true;

    ...
}

您可以在任何地方訪問;

c.pressed; //will return true if you don't change

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM