Не работает слушатель клавиатуры на java gui

Узнай цену своей работы

Формулировка задачи:

Здравствуйте,почему не работает этот код с GUI.Хочу повесить на кнопку jButton1 слушатель addKeyListener(),чтобы по нажатию по <Enter> вычислялась сумма полей(int числа).При нажатию не происходит ничего.
Листинг программы
  1. import javax.swing.JOptionPane;
  2.  
  3. public class NewJFrame extends javax.swing.JFrame {
  4. /**
  5. * Creates new form NewJFrame
  6. */
  7. public NewJFrame() {
  8. initComponents();
  9. }
  10. /**
  11. * This method is called from within the constructor to initialize the form.
  12. * WARNING: Do NOT modify this code. The content of this method is always
  13. * regenerated by the Form Editor.
  14. */
  15. @SuppressWarnings("unchecked")
  16. // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  17. private void initComponents() {
  18. jTextField1 = new javax.swing.JTextField();
  19. jLabel1 = new javax.swing.JLabel();
  20. jTextField2 = new javax.swing.JTextField();
  21. jButton1 = new javax.swing.JButton();
  22. jLabel2 = new javax.swing.JLabel();
  23. setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  24. jTextField1.setText(" ");
  25. jLabel1.setText("+");
  26. jTextField2.setText(" ");
  27. jButton1.setText("jButton1");
  28. /*jButton1.addActionListener(new java.awt.event.ActionListener() {
  29. public void actionPerformed(java.awt.event.ActionEvent evt) {
  30. jButton1ActionPerformed(evt);
  31. }
  32. });*/
  33. jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
  34. public void keyPressed(java.awt.event.KeyEvent evt){
  35. formKeyPressed(evt);
  36. }
  37. });
  38.  
  39. jLabel2.setText(" ");
  40. }// </editor-fold>//GEN-END:initComponents
  41.  
  42. private void jButton1ActionPerformed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
  43. int i=0;int j=0;
  44. try{
  45.  
  46. i=Integer.parseInt(jTextField1.getText());
  47. j=Integer.parseInt(jTextField2.getText());
  48. Integer d=i+j;
  49. jLabel2.setText(d.toString());
  50. }catch(Exception ex){
  51. JOptionPane.showMessageDialog(null,"Введите целое число.");
  52. }//
  53. }//GEN-LAST:event_jButton1ActionPerformed
  54. }
  55. private void formKeyPressed(java.awt.event.KeyEvent evt){
  56. switch(evt.getKeyCode()){
  57. case java.awt.event.KeyEvent.VK_ENTER:
  58. jButton1ActionPerformed(evt);
  59. break;
  60. default:
  61. }
  62. }
  63.  
  64. /**
  65. * @param args the command line arguments
  66. */
  67. public static void main(String args[]) {
  68.  
  69. /* Create and display the form */
  70. java.awt.EventQueue.invokeLater(new Runnable() {
  71. public void run() {
  72. new NewJFrame().setVisible(true);
  73. }
  74. });
  75. }
  76. // Variables declaration - do not modify//GEN-BEGIN:variables
  77. private javax.swing.JButton jButton1;
  78. private javax.swing.JLabel jLabel1;
  79. private javax.swing.JLabel jLabel2;
  80. private javax.swing.JTextField jTextField1;
  81. private javax.swing.JTextField jTextField2;
  82. // End of variables declaration//GEN-END:variables
  83. }
Здесь часть часть кода вырезана,где идет расположение компонентов т.к форму делал в NetBeans.addKeyListener() на jButton1 добавлял в far редакторе.

Решение задачи: «Не работает слушатель клавиатуры на java gui»

textual
Листинг программы
  1. import javax.swing.JOptionPane;
  2.  
  3.  
  4. public class NewJFrame extends javax.swing.JFrame {
  5.  
  6.     /**
  7.      * Creates new form NewJFrame
  8.      */
  9.     public NewJFrame() {
  10.         initComponents();
  11.     jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
  12.             public void keyPressed(java.awt.event.KeyEvent evt){
  13.     formKeyPressed(evt);
  14.                
  15.             }
  16. });
  17.  
  18.     }
  19.  
  20.     /**
  21.      * This method is called from within the constructor to initialize the form.
  22.      * WARNING: Do NOT modify this code. The content of this method is always
  23.      * regenerated by the Form Editor.
  24.      */
  25.     @SuppressWarnings("unchecked")
  26.     // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  27.     private void initComponents() {
  28.  
  29.         jTextField1 = new javax.swing.JTextField();
  30.         jLabel1 = new javax.swing.JLabel();
  31.         jTextField2 = new javax.swing.JTextField();
  32.         jButton1 = new javax.swing.JButton();
  33.         jLabel2 = new javax.swing.JLabel();
  34.  
  35.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  36.  
  37.         jTextField1.setText(" ");
  38.  
  39.         jLabel1.setText("+");
  40.  
  41.         jTextField2.setText(" ");
  42.  
  43.         jButton1.setText("jButton1");
  44.         /*jButton1.addActionListener(new java.awt.event.ActionListener() {
  45.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  46.                 jButton1ActionPerformed(evt);
  47.             }
  48.         });*/
  49.    
  50.  
  51.  
  52.         jLabel2.setText(" ");
  53.  
  54.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  55.         getContentPane().setLayout(layout);
  56.         layout.setHorizontalGroup(
  57.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  58.             .addGroup(layout.createSequentialGroup()
  59.                 .addContainerGap()
  60.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  61.                     .addGroup(layout.createSequentialGroup()
  62.                         .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
  63.                         .addGap(18, 18, 18)
  64.                         .addComponent(jLabel1)
  65.                         .addGap(18, 18, 18)
  66.                         .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
  67.                     .addComponent(jButton1)
  68.                     .addComponent(jLabel2))
  69.                 .addContainerGap(162, Short.MAX_VALUE))
  70.         );
  71.         layout.setVerticalGroup(
  72.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  73.             .addGroup(layout.createSequentialGroup()
  74.                 .addContainerGap()
  75.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  76.                     .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  77.                     .addComponent(jLabel1)
  78.                     .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  79.                 .addGap(18, 18, 18)
  80.                 .addComponent(jButton1)
  81.                 .addGap(18, 18, 18)
  82.                 .addComponent(jLabel2)
  83.                 .addContainerGap(196, Short.MAX_VALUE))
  84.         );
  85.  
  86.         pack();
  87.     }// </editor-fold>//GEN-END:initComponents
  88.  
  89.  
  90.  
  91.     private void jButton1ActionPerformed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
  92. Integer i=0, j=0;
  93.         try{
  94.    
  95.    
  96.      i=Integer.parseInt(jTextField1.getText());
  97.      j=Integer.parseInt(jTextField2.getText());
  98. Integer d=i+j;
  99.     jLabel2.setText(d.toString());        
  100.    
  101. }catch(Exception ex){
  102. JOptionPane.showMessageDialog(null,"Введите целое число!");
  103. }//     }//GEN-LAST:event_jButton1ActionPerformed
  104. }
  105. private void  formKeyPressed(java.awt.event.KeyEvent evt){
  106.  switch(evt.getKeyCode()){
  107. case java.awt.event.KeyEvent.VK_ENTER:
  108. jButton1ActionPerformed(evt);
  109. //System.out.println("ku-ku!");
  110. break;
  111. default:
  112.  
  113. }    
  114.  }            
  115.  
  116.  
  117.     /**
  118.      * @param args the command line arguments
  119.      */
  120.     public static void main(String args[]) {
  121.         /* Set the Nimbus look and feel */
  122.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  123.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  124.          * For details see [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url]
  125.          */
  126.         try {
  127.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  128.                 if ("Nimbus".equals(info.getName())) {
  129.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  130.                     break;
  131.                 }
  132.             }
  133.         } catch (ClassNotFoundException ex) {
  134.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  135.         } catch (InstantiationException ex) {
  136.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  137.         } catch (IllegalAccessException ex) {
  138.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  139.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  140.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  141.         }
  142.         //</editor-fold>
  143.  
  144.         /* Create and display the form */
  145.         java.awt.EventQueue.invokeLater(new Runnable() {
  146.             public void run() {
  147.                 new NewJFrame().setVisible(true);
  148.             }
  149.         });
  150.     }
  151.  
  152.     // Variables declaration - do not modify//GEN-BEGIN:variables
  153.     private javax.swing.JButton jButton1;
  154.     private javax.swing.JLabel jLabel1;
  155.     private javax.swing.JLabel jLabel2;
  156.     private javax.swing.JTextField jTextField1;
  157.     private javax.swing.JTextField jTextField2;
  158.     // End of variables declaration//GEN-END:variables
  159. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

8   голосов , оценка 3.75 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут