gpt4 book ai didi

java - 如何在没有按钮的情况下主动(立即)检查 JFrame 表单中文本框的值?

转载 作者:行者123 更新时间:2023-11-29 02:58:10 29 4
gpt4 key购买 nike

我希望能够在文本框中输入内容,当用户在文本框中输入内容时,我希望程序无需单击按钮即可自动读取文本框。

例子:用户类型:“abcd”当用户输入时,程序会显示每个字母对应的数字。

程序输出:“1234”

如:a -> 1; b -> 2;等等

我正在使用“private void mycode()”写我的代码。我看到,如果我将其设为静态,我可以使用 java.util.concurrent.TimeUnit ( https://stackoverflow.com/a/24104427/12577450 ),但是 mycode() 将无法正确处理我的变量。

有人可以帮帮我吗?

最佳答案

您可以使用 DocumentListener 类。

看看https://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentListener.html

import javax.swing.*;
import javax.swing.event.*;
import java.io.Serializable;

public class MyFrame extends JFrame implements Serializable {
private static final long serialVersionUID = 123;
private JTextField field1, field2;

public MyFrame() {
super.setSize(600, 400);
super.setPreferredSize(new java.awt.Dimension(600, 400));
super.setResizable(false);
field1 = new JTextField();
field2 = new JTextField();
super.add(field1);
super.add(field2);
field1.setLocation(0, 0);
field1.setSize(600, 200);
field2.setLocation(0, 200);
field2.setSize(600, 200);
field2.setEditable(false);
super.setLocationRelativeTo(null);
field1.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
f();
}
public void removeUpdate(DocumentEvent e) {
f();
}
public void insertUpdate(DocumentEvent e) {
f();
}
public void f(){
String new_str = "";
for (char c : field1.getText().toCharArray()) {
if (c >= 'a' && c <= 'z')
new_str += (int) (c - 'a' + 1); // is this what you want?
else
new_str += c;
}
field2.setText(new_str);
field2.setBounds(0, 200, 600, 200);
}
});
super.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
super.setVisible(true);
}

public static void main(String[] args) {
new MyFrame();
}
}

关于java - 如何在没有按钮的情况下主动(立即)检查 JFrame 表单中文本框的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59440214/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com