Не работает слушатель клавиатуры на java gui
Формулировка задачи:
Здравствуйте,почему не работает этот код с GUI.Хочу повесить на кнопку jButton1 слушатель addKeyListener(),чтобы по нажатию
по <Enter> вычислялась сумма полей(int числа).При нажатию не происходит ничего.
Здесь часть часть кода вырезана,где идет расположение компонентов т.к форму делал в NetBeans.addKeyListener() на jButton1 добавлял в far редакторе.
import javax.swing.JOptionPane; public class NewJFrame extends javax.swing.JFrame { /** * Creates new form NewJFrame */ public NewJFrame() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextField1.setText(" "); jLabel1.setText("+"); jTextField2.setText(" "); jButton1.setText("jButton1"); /*jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } });*/ jButton1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt){ formKeyPressed(evt); } }); jLabel2.setText(" "); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed int i=0;int j=0; try{ i=Integer.parseInt(jTextField1.getText()); j=Integer.parseInt(jTextField2.getText()); Integer d=i+j; jLabel2.setText(d.toString()); }catch(Exception ex){ JOptionPane.showMessageDialog(null,"Введите целое число."); }// }//GEN-LAST:event_jButton1ActionPerformed } private void formKeyPressed(java.awt.event.KeyEvent evt){ switch(evt.getKeyCode()){ case java.awt.event.KeyEvent.VK_ENTER: jButton1ActionPerformed(evt); break; default: } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
Решение задачи: «Не работает слушатель клавиатуры на java gui»
textual
Листинг программы
import javax.swing.JOptionPane; public class NewJFrame extends javax.swing.JFrame { /** * Creates new form NewJFrame */ public NewJFrame() { initComponents(); jButton1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt){ formKeyPressed(evt); } }); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextField1.setText(" "); jLabel1.setText("+"); jTextField2.setText(" "); jButton1.setText("jButton1"); /*jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } });*/ jLabel2.setText(" "); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButton1) .addComponent(jLabel2)) .addContainerGap(162, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jButton1) .addGap(18, 18, 18) .addComponent(jLabel2) .addContainerGap(196, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed Integer i=0, j=0; try{ i=Integer.parseInt(jTextField1.getText()); j=Integer.parseInt(jTextField2.getText()); Integer d=i+j; jLabel2.setText(d.toString()); }catch(Exception ex){ JOptionPane.showMessageDialog(null,"Введите целое число!"); }// }//GEN-LAST:event_jButton1ActionPerformed } private void formKeyPressed(java.awt.event.KeyEvent evt){ switch(evt.getKeyCode()){ case java.awt.event.KeyEvent.VK_ENTER: jButton1ActionPerformed(evt); //System.out.println("ku-ku!"); break; default: } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url] */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д