2016-03-26 14 views
0

Klavye denetimlerim, oluşturduğum Grafik GUI panelindeki (JPanel) bir düğmeyi tıklattıktan sonra çalışmayı durdurur. Aşağıda ana sınıfımın kodu var. Anahtarlistener kodumu kontrolör sınıfına koydum. Klavye odağını ayarlamaya çalıştım ama çalışmıyor. JPanel sınıf kodumu da ekledim. Odağı yanlış olarak ayarlamayı denedim ve hala çalışmıyor. Birisi odakların düğmelerden neden kaçmadığını açıklayabilir mi lütfen?Klavye denetimleri, JPanel'deki bir düğmeyi tıklattıktan sonra çalışmayı durdurur mu?

Ana sınıfı

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 sınıfı

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     

}

cevap

2

Sen odak sorunlarınızın olup olmadığını yerine KeyListener ait Key Bindings kullanarak denemek isteyebilirsiniz. Çoğu zaman bir çok Swing bileşeniniz olduğunda, KeyListener ürününüzün kayıtlı olduğu bileşen odağı kaybedebilir.

Düğmelerdeki setFocusable(false)'un KeyListener ile kaydettiğiniz bileşenin odağını yeniden elde etmesine neden olacağını bilmiyorum, ancak bunun önerilmez. Bence diğer bileşenlerden odaklanmayı zorlayabilirsin ama bu uzun vadede çok iyi ölçeklenemezdi.