为什么 JFormattedTextField 不支持 actionPerformed
Why JFormattedTextField does not suppport actionPerformed
我的表单中有一个 JFormattedTextField
,我希望在输入值后,当用户按下回车键时,它应该移动到下一个字段。但在我所有的尝试之后,我都没有这样做。
为此,我将 ActionListener
附加到 JFormattedTextField
但按下 Enter 永远不会触发事件。为什么?有人可以帮忙吗?
public class Test extends javax.swing.JFrame {
/**
* Creates new form Test
*/
public Test() {
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() {
ftf = new javax.swing.JFormattedTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
ftf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
ftf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ftfActionPerformed(evt);
}
});
jLabel1.setText("JFormattedTextField Action Test");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ftf, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(167, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(ftf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(238, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void ftfActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JOptionPane.showMessageDialog(this, "Enter Pressed");
}
/**
* @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(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Test.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 Test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JFormattedTextField ftf;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
您需要添加一个Action
:
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
//preform your action here.
}
};
ftf.addActionListener( action );
当按下回车键时执行动作。
两种方式都可以。
1. 有一个简单的技巧。使用所有按钮构建框架后,请执行以下操作:
frame.getRootPane().setDefaultButton(submitButton);
对于每一帧,您可以设置一个默认按钮,该按钮将自动侦听 Enter 键(可能还有我不知道的其他事件)。当您在该帧中按下回车键时,将调用 ActionListeners 的 actionPerformed() 方法。
2. JFormattedTextField
旨在像 JButton 一样使用 ActionListener
。参见 JFormattedTextField 的 addActionListener() 方法。
例如:
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("some action");
}
};
JFormattedTextField textField = new JFormattedTextField(10);
textField.addActionListener( action );
现在当使用 Enter
键时会触发事件。
此外,一个额外的好处是您可以与按钮共享侦听器,即使您不想将按钮设为默认按钮。
JButton button = new JButton("Do Something");
button.addActionListener( action );
请注意,此示例使用了一个实现 ActionListener 的 Action,因为 Action 是具有附加功能的较新 API。例如,您可以禁用将禁用文本字段和按钮事件的操作。
您可以将 Enter
键绑定到 JFormattedTextField
并在按下 Enter
时调用 AbstractAction
而不是 ActionListener
:
InputMap inputMap = ftf.getInputMap(JComponent.WHEN_FOCUSED);
inputMap.put(KeyStroke.getKeyStroke((char) KeyEvent.VK_ENTER), "enterPressed");
ftf.getActionMap().put("enterPressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("actionPerformed");
ftfActionPerformed(e);
}
});
当 JFormattedTextField
获得焦点时,它将处理 actionPerformed
方法中的 Enter
键
我的表单中有一个 JFormattedTextField
,我希望在输入值后,当用户按下回车键时,它应该移动到下一个字段。但在我所有的尝试之后,我都没有这样做。
为此,我将 ActionListener
附加到 JFormattedTextField
但按下 Enter 永远不会触发事件。为什么?有人可以帮忙吗?
public class Test extends javax.swing.JFrame {
/**
* Creates new form Test
*/
public Test() {
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() {
ftf = new javax.swing.JFormattedTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
ftf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
ftf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ftfActionPerformed(evt);
}
});
jLabel1.setText("JFormattedTextField Action Test");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ftf, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(167, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(ftf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(238, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void ftfActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JOptionPane.showMessageDialog(this, "Enter Pressed");
}
/**
* @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(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Test.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 Test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JFormattedTextField ftf;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
您需要添加一个Action
:
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
//preform your action here.
}
};
ftf.addActionListener( action );
当按下回车键时执行动作。
两种方式都可以。
1. 有一个简单的技巧。使用所有按钮构建框架后,请执行以下操作:
frame.getRootPane().setDefaultButton(submitButton);
对于每一帧,您可以设置一个默认按钮,该按钮将自动侦听 Enter 键(可能还有我不知道的其他事件)。当您在该帧中按下回车键时,将调用 ActionListeners 的 actionPerformed() 方法。
2. JFormattedTextField
旨在像 JButton 一样使用 ActionListener
。参见 JFormattedTextField 的 addActionListener() 方法。
例如:
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("some action");
}
};
JFormattedTextField textField = new JFormattedTextField(10);
textField.addActionListener( action );
现在当使用 Enter
键时会触发事件。
此外,一个额外的好处是您可以与按钮共享侦听器,即使您不想将按钮设为默认按钮。
JButton button = new JButton("Do Something");
button.addActionListener( action );
请注意,此示例使用了一个实现 ActionListener 的 Action,因为 Action 是具有附加功能的较新 API。例如,您可以禁用将禁用文本字段和按钮事件的操作。
您可以将 Enter
键绑定到 JFormattedTextField
并在按下 Enter
时调用 AbstractAction
而不是 ActionListener
:
InputMap inputMap = ftf.getInputMap(JComponent.WHEN_FOCUSED);
inputMap.put(KeyStroke.getKeyStroke((char) KeyEvent.VK_ENTER), "enterPressed");
ftf.getActionMap().put("enterPressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("actionPerformed");
ftfActionPerformed(e);
}
});
当 JFormattedTextField
获得焦点时,它将处理 actionPerformed
方法中的 Enter
键