我正在尝试更改按钮的背景颜色,当按下具有相同字母/符号的按键但问题是此代码不适用于符号和空格,我做错了什么以及如何修复?
以下是代码:
private String names[]={"`"," 1 "," 2 "," 3 "," 4 "," 5 "," 6 "," 7 "," 8 "," 9 "," 0 "," - "," + "," Backspace "
," Tab "," Q "," W "," E "," R "," T "," Y "," U "," I "," O "," P "," [ "," ] "," \\ "
," Caps Lock "," A "," S "," D "," F "," G "," H "," J "," K "," L "," ; "," ' "," Enter "
," Shift "," Z "," X "," C "," V "," B "," N "," M "," , "," . "," / "," ^ "
," "," < "," ! "," > "};
public void keyPressed(KeyEvent event)
{
int code= event.getKeyCode();
String x;
for(int i=0;i<names.length;i++)
{
s=names[i];
x=s.trim();
if(x.contentEquals(event.getKeyText(code)) )
{
backColor=but[i].getBackground();
but[i].setBackground(Color.RED);
break;
}
}
}
public void keyReleased(KeyEvent event)
{
String x;
int code= event.getKeyCode();
for(int i=0;i<names.length;i++)
{
s=names[i];
x=s.trim();
if(x.contentEquals(event.getKeyText(code)))
{System.out.println("outside");
but[i].setBackground(backColor);
break;
}
}
}
此致
答案 0 :(得分:1)
我会看一下你names
数组并将其与KeyEvent#getKeyText
我的小测试程序输出了这个...
[PRESSED ] "Space"
[TYPED ] "Unknown keyCode: 0x0"
[RELEASED] "Space"
[PRESSED ] "Enter"
[TYPED ] "Unknown keyCode: 0x0"
[RELEASED] "Enter"
你names
数组的空间存储为" Space "
,永远不会匹配。
你不应该依赖KeyEvent#getKetText
的结果,因为它没有考虑键盘的当前扩展状态(即,如果按下shift),这可能会改变键的状态。
例如,如果我输入['],我的测试程序将输出Quote
,但如果我输入[shift +'](应生成[“]),它仍会显示Quote
。甚至让我开始{和[:P
如果您对显示击键文字不感兴趣,最好依靠虚拟键值
public class PaintMyKeys {
public static void main(String[] args) {
new PaintMyKeys();
}
public PaintMyKeys() {
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 PaintMyKeysPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintMyKeysPane extends JPanel {
private JLabel label;
public PaintMyKeysPane() {
setLayout(new BorderLayout());
label = new JLabel("Press space to change colors", JLabel.CENTER);
label.setOpaque(true);
add(label);
addKeyListener(new KeyAdapter() {
protected int random() {
return (int)Math.round(Math.random() * 255);
}
protected Color randomColor() {
int r = random();
int g = random();
int b = random();
int a = random();
return new Color(r, g, b, a);
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
label.setBackground(randomColor());
label.setForeground(randomColor());
}
}
});
setFocusable(true);
requestFocusInWindow();
}
}
}
答案 1 :(得分:0)
作为一般规则,getKeyText()
的结果在浏览器中并不统一,与实际文本键(字母和数字)的其他任何内容无关。
我认为您应该重新考虑使用getKeyCode()
的方法。
有用的链接:
答案 2 :(得分:0)
据我所知,getKeyText()方法返回单词而不是大多数符号(例如“。”的代码产生“PERIOD”)。不要在名字数组中使用“。”等,而是使用“PERIOD”和“SPACE”。
Here是getKeyText()方法的代码,它会准确显示哪些字符将返回密钥的名称。