我有一个 JTextField
和一个 JLabel
;如果用户键入特殊字符,例如 /
,我希望 JLabel
为 setVisible(true)
。
我希望用户无需按任何按钮即可完成此操作,但在输入完成时“实时”,对于插入的每个新字符,都会进行检查。我该如何做这样的事情?
最佳答案
使用 DocumentListener 的简单解决方案:
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class DemoFrame extends JFrame {
JTextField tf;
JLabel lbl;
public DemoFrame() {
tf = new JTextField(10);
lbl = new JLabel("Test");
tf.getDocument().addDocumentListener(new DemoDocumentListener());
lbl.setVisible(false);
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(tf);
this.add(lbl);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 100);
this.setVisible(true);
}
public void checkForSpecialString() {
if (tf.getText().contains("/")) {
lbl.setVisible(true);
} else {
lbl.setVisible(false);
}
}
class DemoDocumentListener implements DocumentListener {
@Override
public void insertUpdate(DocumentEvent e) {
checkForSpecialString();
}
@Override
public void removeUpdate(DocumentEvent e) {
checkForSpecialString();
}
@Override
public void changedUpdate(DocumentEvent e) {
checkForSpecialString();
}
}
public static void main(String[] args) {
new DemoFrame();
}
}
关于Java 在输入时创建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567803/