我正在尝试使用 JButton count
来计算输入到 JTextField t
中的字符数。我是 Java 和 GUI 的新手,但这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 extends Frame implements ActionListener{
TextField t;
Button count;
int a;
Choice choice;
public GUI1(){
this.t = new TextField("", 30);
this.count = new Button("count");
this.count.addActionListener(this);
JTextField x = new JTextField();
x.setEditable(false);
this.setTitle("Character count");
this.setLayout(new FlowLayout());
this.add(x);
this.add(t);
this.add(count);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()== this.count)
t.setText(choice.getSelectedItem()+ " " +a);
}
我还试图在另一个不可编辑的 JTextField x
中输入值。感谢您的帮助。
最佳答案
将此添加到您的代码中
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
a = t.getText().length();
}
});
或
你可以像这样使用lambda表达式
count.addActionListener(e -> a = t.getText().length());
更多 http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
关于java - 我正在尝试制作一个按钮来计算文本字段中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33919273/