【发布时间】:2016-03-26 13:30:59
【问题描述】:
单击我创建的图形 gui 面板 (JPanel) 中的按钮后,我的键盘控件停止工作。下面是我的主要课程的代码。我将我的 keylistener 代码放在控制器类中。我试图设置键盘焦点,但它不起作用。我还添加了我的 JPanel 类代码。我尝试将焦点设置为错误,但它仍然无法正常工作。有人可以解释一下为什么焦点没有从按钮上转移吗?
主类
Graphical gui = new Graphical(view, getPlayer());
frame.add(gui, BorderLayout.SOUTH);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
// Get keyboard focus.
frame.requestFocus();
view.addMouseListener(new MouseHandler(view));
controller = new Controller(world.getPlayer());
frame.addKeyListener(controller);
JPanel 类
public class Graphical extends javax.swing.JPanel {
private UserView view;
private Snowman snowman;
private Game game;
public Graphical(UserView view, Snowman snowman) {
this.view = view;
this.snowman = snowman;
initComponents();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println("You are now playing as a snowman!");
snowman.changeCharacter1();
jButton1.setFocusable(false);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println("You are now playing as a jellyfish!");
snowman.changeCharacter2();
jButton2.setFocusable(false);
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
new Game();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
// End of variables declaration
}
【问题讨论】:
标签: java swing jpanel keylistener