java - 如何使用 KeyListener 根据按下的键显示不同的字符串?

标签 java swing user-interface jframe keylistener

别紧张,我对 Java 编程(尤其是 swing)还很陌生,并且我正在尝试学习 GUI 编程的基础知识。

我希望能够提示用户在文本框中输入某个键,然后单击按钮以根据他们输入的键显示一串文本。这是我到目前为止所拥有的:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class LeeSinAbilities extends JFrame
{
    private JLabel leeSin;
    private JTextField ability;
    private JButton c;
    private JLabel aName;
    private static final long serialVersionUID = 1L;
    public LeeSinAbilities()
    {
       super("Lee Sin's Abilities");
       setLayout(new FlowLayout());
       setResizable(true);
       setSize(500, 500);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       JLabel leeSin = new JLabel("Enter an ability key to see Lee Sin's ability names! (q, w, e, r)");
       add(leeSin);

       JTextField ability = new JTextField("Enter abilities here: ", 1);
       add(ability);

       JButton go = new JButton("Get Ability Name");
       add(go);

       JLabel aName = new JLabel("");
       add(aName);

       event e = new event();
       go.addActionListener(e);
    }
    public static void main(String [] args){
       new LeeSinAbilities().setVisible(true);
    }
    public class event implements ActionListener{
        public void actionPerformed(ActionEvent e){
            String abilityName = ability.getText();
               if(abilityName.equalsIgnoreCase("q")){
                   aName.setText("Sonic Wave / Resonating Strike");
                }
               else if(abilityName.equalsIgnoreCase("w")){
                   aName.setText("Safeguard / Iron Will");
                }
                else if(abilityName.equalsIgnoreCase("e")){
                   aName.setText("Tempest / Cripple");
                }
                else if(abilityName.equalsIgnoreCase("r")){
                   aName.setText("Dragon's Rage");
                }
                else
                   aName.setText("Brutha please -_-...q, w, e, or r!");
        }
    }
}

我意识到 ActionListener 不是正确使用的事件,我只是不确定该放什么(我猜是 KeyListener)。非常感谢所有评论/建议。

最佳答案

第一个问题(我认为是 NullPointerException)是由于您正在隐藏变量......

public class LeeSinAbilities extends JFrame
{
    //...
    // This is a instance variable named ability
    private JTextField ability;
    //...
    public LeeSinAbilities()
    {
       //...
       // This is a local variable named ability , which
       // is now shadowing the instance variable...
       JTextField ability = new JTextField("Enter abilities here: ", 1);
       //...
    }
    public class event implements ActionListener{
        public void actionPerformed(ActionEvent e){
            // This will be `null` as it's referencing the
            // instance variable...
            String abilityName = ability.getText();
            //...
        }
    }
}

所以不要使用...

       JTextField ability = new JTextField("Enter abilities here: ", 1);

你应该使用...

       ability = new JTextField("Enter abilities here: ", 1);

这将防止 actionPerformed 方法中发生 NullPointerException

已更新

现在,如果您想响应按键事件,最好的方法是使用 Key Bindings API,例如

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class KeyPrompt {

    public static void main(String[] args) {
        new KeyPrompt();
    }

    public KeyPrompt() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.setSize(400, 200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel aName;

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            add(new JLabel("Enter an ability key to see Lee Sin's ability names! (q, w, e, r)"), gbc);
            aName = new JLabel("");
            add(aName, gbc);

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0), "QAbility");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "WAbility");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_E, 0), "EAbility");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0), "RAbility");

            am.put("QAbility", new MessageAction(aName, "Sonic Wave / Resonating Strike"));
            am.put("WAbility", new MessageAction(aName, "Safeguard / Iron Will"));
            am.put("EAbility", new MessageAction(aName, "Tempest / Cripple"));
            am.put("RAbility", new MessageAction(aName, "Dragon's Rage"));

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.dispose();
        }

        public class MessageAction extends AbstractAction {

            private final String msg;
            private final JLabel msgLabel;

            public MessageAction(JLabel msgLabel, String msg) {
                this.msgLabel = msgLabel;
                this.msg = msg;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                msgLabel.setText(msg);
            }

        }


    }

}

它可以根据您的需求更好地控制焦点要求...

关于java - 如何使用 KeyListener 根据按下的键显示不同的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20461441/

相关文章:

javascript - 如何将边框半径应用于具有水平滚动的分隔表行?

java - Spring boot 项目生成问题

java - 如何在 Java Swing 应用程序中管理来自 Controller 的 View 更新

java - 在游戏中正确实现延迟

Java swing,使用 Eclipse 从数据库中检索图像时出错

java - 从线程框架上拆下面板

android - CollapsingToolbarLayout 问题 : overlapping UI with ToolBar

java - (java.security.InvalidKeyException) 在 cipher.init(Cipher.DECRYPT_MODE, key) 出现预期错误时未设置 IV

java - 父类(super class)引用不应该能够调用其子类独有的方法,但是

Java Swing - 如何暂停方法并等待按键?