【发布时间】:2019-01-17 13:22:41
【问题描述】:
我用java编写了一个基本的控制板gui。当按下箭头键时,文本将显示在键盘上按下了哪个按钮,并且按钮会改变颜色。
问题是这个程序在 Windows 中运行良好,但是当我在运行名为 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
}
}
【问题讨论】:
-
这真的在树莓派上运行吗?
标签: java swing raspberry-pi