java - 我正在尝试制作一个按钮来计算文本字段中的字符数

标签 java user-interface

我正在尝试使用 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/

相关文章:

java - 比较来自 DB2 中不同数据库的两个表

java - Spring Data Elasticsearch将Elasticsearch聚合查询转换为代码

Java套接字: Application with both server and client on same machine

java - java中的HTTPS和HTTP连接

android - 在 Android Touch 事件中看不到点击涟漪效应

java - JProgressBar - 在我调用它的类中不起作用

java - 通过在java中标准化来调整列表

java - 将图像添加到 GUI

user-interface - 如何在 Google 脚本编辑器中更改背景颜色

windows - Windows GUI 中的 Unix 工具