2017-01-23 63 views
0

我有一个模拟摄氏华氏转换器的JFrame。 我想要做的是每当ENTER键被按下时调用“convert”按钮动作。为什么这个Java键绑定不起作用?

我试过定义默认按钮(但它不起作用)。

我的代码现在看起来像这样:

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

欢迎来到SO。请看看如何创建[mcve]。我摔倒了,你可以大幅缩短这个特定问题的代码长度。 – AxelH

+0

你可能会在这里找到你想要的东西:[允许“Enter”键按下提交按钮,而不是只使用MouseClick](http://stackoverflow.com/q/13731710/4391450)如果是这样,请做一些先研究。 – AxelH

回答

0

没什么特别的需要,只需添加到您的EditText设置。

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

'edittext.addActionListener((ae) - > button_convertActionPerformed(ae));'会导致更少的意外 – MadProgrammer

+0

为真,但我建议将该函数更改为: private void button_convertActionPerformed() – Beowolve