2017-01-23 2 views
0

J'ai un JFrame qui simule un simple convertisseur de Celsius en Fahrenheit. Ce que j'essaie de faire est d'appeler l'action du bouton "Convertir" chaque fois que la touche ENTER est enfoncée.Pourquoi cette liaison de touches Java ne fonctionne pas?

J'ai essayé de définir le bouton par défaut (mais il ne fonctionne pas).

Mon code ressemble maintenant à ceci:

public class TemperatureConverterGUI extends javax.swing.JFrame { 

/** 
* Creates new form TemperatureConverterGUI 
*/ 
public TemperatureConverterGUI() { 
    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">       
private void initComponents() { 

    button_convert = new javax.swing.JButton(); 
    edittext = new javax.swing.JFormattedTextField(); 
    label = new javax.swing.JLabel(); 
    label_resultat = new javax.swing.JLabel(); 
    resultat = new javax.swing.JLabel(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    button_convert.setText("Converteix"); 
    button_convert.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      button_convertActionPerformed(evt); 
     } 
    }); 

    edittext.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0")))); 
    edittext.setHorizontalAlignment(javax.swing.JTextField.CENTER); 
    edittext.setToolTipText("Introdueix un número en Fahrenheit"); 

    label.setText("Introdueix un número en Fahrenheit:"); 

    label_resultat.setText("Resultat: "); 

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
      .addContainerGap(49, Short.MAX_VALUE) 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(layout.createSequentialGroup() 
        .addComponent(label_resultat) 
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
        .addComponent(resultat)) 
       .addComponent(button_convert) 
       .addComponent(label) 
       .addComponent(edittext, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)) 
      .addGap(90, 90, 90)) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
      .addContainerGap(65, Short.MAX_VALUE) 
      .addComponent(label) 
      .addGap(12, 12, 12) 
      .addComponent(edittext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addGap(31, 31, 31) 
      .addComponent(button_convert) 
      .addGap(48, 48, 48) 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
       .addComponent(label_resultat) 
       .addComponent(resultat)) 
      .addGap(70, 70, 70)) 
    ); 

    pack(); 
}// </editor-fold>       

private void button_convertActionPerformed(java.awt.event.ActionEvent evt) {            
    int f = Integer.valueOf(edittext.getText()); 
    int c = VisualTemperatureConverter.FahrenheitToCelsius(f); 
    resultat.setText(String.valueOf(c)); 
}            

/** 
* @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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
    */ 
    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(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 

    **TemperatureConverterGUI frame = new TemperatureConverterGUI(); 

    frame.button_convert.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "enter"); 
    frame.button_convert.getActionMap().put("enter", frame.button_convert.getAction());** 


    frame.setVisible(true); 
} 

// Variables declaration - do not modify      
private javax.swing.JButton button_convert; 
private javax.swing.JFormattedTextField edittext; 
private javax.swing.JLabel label; 
private javax.swing.JLabel label_resultat; 
private javax.swing.JLabel resultat; 
// End of variables declaration 
} 
+1

Bienvenue sur le SO. S'il vous plaît, voyez comment créer un [mcve]. Je suis tombé, vous pourriez réduire la longueur du code pour cette question spécifique de façon drastique. – AxelH

+0

Vous pouvez trouver ce que vous voulez là: [Permettre la touche « Entrée » pour appuyer sur le bouton d'envoi, par opposition à l'aide que MouseClick] (http://stackoverflow.com/q/13731710/4391450) Si oui, s'il vous plaît faire quelques recherche d'abord. – AxelH

Répondre

0

Rien de fantaisie nécessaire, il suffit d'ajouter ceci à votre configuration edittext.

edittext.addActionListener((ae)-> button_convertActionPerformed(null)); 
+0

'edittext.addActionListener ((ae) -> button_convertActionPerformed (ae));' causerait moins de surprises – MadProgrammer

+0

vrai, mais je conseillerais de changer la fonction pour: private void button_convertActionPerformed() – Beowolve