【问题标题】:Keyboard controls stop working after I click a button in the JPanel?单击 JPanel 中的按钮后,键盘控件停止工作?
【发布时间】: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


    【解决方案1】:

    如果您遇到焦点问题,您可能想尝试使用Key Bindings 而不是KeyListener。通常,当您有很多 Swing 组件时,KeyListener 注册的组件可能会失去焦点。

    我不知道按钮上的setFocusable(false) 是否会导致您重新获得使用KeyListener 注册的组件的焦点,但我知道不建议这样做。我想您可以强制从其他组件集中注意力,但从长远来看,这不会很好地扩展。

    【讨论】:

      猜你喜欢
      • 2012-08-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多