[英]Is it Possible to Add ActionListener in the JFormattedTextField?
您好,我目前在我的Java文件中工作。 我想在按下Enter鍵時在JFormattedTextField上添加一個事件。 這是我的代碼
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.text.ParseException;
public class Test extends JFrame implements ActionListener
{
JFormattedTextField phoneField;
Test()
{
setTitle("JFormatted Text");
setLayout(null);
MaskFormatter mask = null;
try {
mask = new MaskFormatter("##########");
} catch (ParseException e) {
e.printStackTrace();
}
phoneField = new JFormattedTextField(mask);
phoneField.setBounds(20, 20, 150, 30);
phoneField.addActionListener(this);
setVisible(true);
setSize(200, 200);
getContentPane().add(phoneField);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new Test();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== phoneField)
{
System.out.println("The numbers you enter are "+phoneField.getText());
}
}
}
可以,但是用戶需要輸入10位數字。
將一個ActionListener
添加到該字段。 它比使用(低級) KeyListener
更好,並且將符合OS接受的“進入終點”的要求。
不要使用KeyListener
而要使用DocumentListener 。
它具有以下方法來捕獲JTextField
的更改
JTextField textField = new JTextField();
textField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent arg0) {
// Gives notification that a portion of the document has been removed.
}
@Override
public void insertUpdate(DocumentEvent arg0) {
// Gives notification that there was an insert into the document.
}
@Override
public void changedUpdate(DocumentEvent arg0) {
// Gives notification that an attribute or set of attributes changed.
}
});
您可以改為添加keyListener。
phonefield.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if(evt.getKeyCode() == evt.VK_ENTER){
System.out.println("The numbers you enter are "+phoneField.getText());
}
}
});
如果這不是您的問題,則應擴大一點並加以澄清。
編輯:正如評論和其他答案所指出的,您應該改為使用ActionListener
。 推理可以在下面找到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.