我在java中编写了一个基本的控制板gui。按下箭头键时,文本将显示键盘上按下的按钮,按钮将改变颜色。
问题是这个程序在windows中工作正常,但是当我在我的覆盆子pi上运行一个名为raspbian的linux版本时,这似乎不起作用。当我按下按钮时,程序没有做任何事情。
package finalRobotControl;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.xml.bind.Marshaller.Listener;
public class Main implements KeyListener{
public static JButton buttonLeft;
public static JButton buttonRight;
public static JButton buttonUp;
public static JButton buttonDown;
public static JLabel stage;
public static void main(String [] args){
JFrame window = new JFrame("RobotController");
window.setVisible(true);
window.setSize(200, 200);
window.setPreferredSize(new Dimension(400, 200));
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
//add panel to window
window.add(panel);
stage = new JLabel("");
stage.setBounds(85, 65, 50, 35);
panel.add(stage);
buttonLeft = new JButton("←");
buttonLeft.setBounds(10, 65, 50, 35);
//buttonLeft.setBackground(Color.BLUE);
panel.add(buttonLeft);
buttonRight = new JButton("→");
buttonRight.setBounds(130, 65, 50, 35);
panel.add(buttonRight);
buttonUp = new JButton("↑");
buttonUp.setBounds(70, 25, 50, 35);
panel.add(buttonUp);
buttonDown = new JButton("↓");
buttonDown.setBounds(70, 105, 50, 35);
panel.add(buttonDown);
window.addKeyListener(new Main());
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode() == KeyEvent.VK_LEFT){
buttonLeft.setBackground(Color.WHITE);
System.out.println("Left");
stage.setText("Left");
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
buttonRight.setBackground(Color.WHITE);
System.out.println("Right");
stage.setText("Right");
}
if(e.getKeyCode() == KeyEvent.VK_UP){
buttonUp.setBackground(Color.WHITE);
System.out.println("Up");
stage.setText("Up");
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
buttonDown.setBackground(Color.WHITE);
System.out.println("Down");
stage.setText("Down");
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
JButton lol = new JButton();
if(e.getKeyCode() == KeyEvent.VK_LEFT){
buttonLeft.setBackground(lol.getBackground());
stage.setText("");
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
buttonRight.setBackground(lol.getBackground());
stage.setText("");
}
if(e.getKeyCode() == KeyEvent.VK_UP){
buttonUp.setBackground(lol.getBackground());
stage.setText("");
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
buttonDown.setBackground(lol.getBackground());
stage.setText("");
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:1)
KeyListener
众所周知,因为它会产生KeyEvent
时的挑剔。 KeyListener
只会在注册到IS的组件可调焦并且HAS焦点时生成KeyEvent
。
将KeyListener直接添加到窗口会使其变得更加困难,因为窗口和使用之间可能存在任意数量的组件,这可能会导致焦点化。
相反,你应该使用Key Bindings API,它允许你控制生成关键事件所需的焦点水平