[英]How to get text and respond to enter press on JFormattedTextField
我最近在我的JFormattedTextField
類中添加了MaskFormatter
。 以前, ActionListener
響應代碼並使用.getText()
方法獲取文本可以.getText()
工作。 使用新的MaskFormatter
,文本將返回“”,並且輸入按不起作用( ActionListener
停止響應該框)。
這是整個JFormattedTextField類:
package swing;
import game.Main;
import java.awt.Font;
import javax.swing.JFormattedTextField;
import javax.swing.text.MaskFormatter;
import window.Listener;
@SuppressWarnings("serial")
public class TextField extends JFormattedTextField
{
public TextField(int size, String text)
//TODO limit to number input and 3 character input only
{
super(createFormatter());
Font font = new Font("AGENCY FB", Font.BOLD, 30);
this.setFont(font);
this.setColumns(size);
this.setSize(100, 100);
this.setText(text);
}
private static MaskFormatter createFormatter()
{
MaskFormatter formatter = null;
try
{
formatter = new MaskFormatter("###");
}
catch (java.text.ParseException exc)
{
System.err.println("formatter is bad: " + exc.getMessage());
System.exit(-1);
}
return formatter;
}
}
輸入 3位數字,然后按Enter ,它對我有用。
public class FieldAction extends JFrame {
FieldAction() {
MaskFormatter mask = null;
try {
mask = new MaskFormatter("###");
} catch (ParseException e) {
e.printStackTrace();
}
final JFormattedTextField textField = new JFormattedTextField(mask);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(textField.getText());
}
});
add(textField, BorderLayout.CENTER);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
new FieldAction();
}
}
我猜下面的代碼可以為您工作。 這樣,無論何時按下回車鍵,您都可以看到輸入的文本。
addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
System.out.println(this.getText().trim());
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.