java如何使用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)非常感谢所有意见/建议
# 1 楼答案
第一个问题(我认为是
NullPointerException
)是因为你在隐藏你的变量所以不用
你应该用
这将防止
NullPointerException
发生在actionPerformed
方法中已更新
现在,如果您想响应密钥事件,最好的方法是使用密钥绑定API,例如
它可以根据您的需要更好地控制焦点要求