简体   繁体   中英

Java GUI Real Time Word Counter

I was checking out the example projects that people do when starting to learn Java and GUI, I was faced with a bunch of word/letter count programs such as:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Counter extends JFrame implements ActionListener{
    JLabel lb1,lb2;
    JTextArea ta;
    JButton b;
    JButton pad,text;
    Counter(){
        super("Char Word Count Tool - JTP");
        lb1=new JLabel("Characters: ");
        lb1.setBounds(50,50,100,20);
        lb2=new JLabel("Words: ");
        lb2.setBounds(50,80,100,20);

        ta=new JTextArea();
        ta.setBounds(50,110,300,200);

        b=new JButton("Count");
        b.setBounds(50,320, 80,30);//x,y,w,h  
        b.addActionListener(this);

        add(lb1);add(lb2);add(ta);add(b);

        setSize(400,400);
        setLayout(null);//using no layout manager  
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent e){
        if(e.getSource()==b){
            String text=ta.getText();
            lb1.setText("Characters: "+text.length());
            String words[]=text.split("\\s");
            lb2.setText("Words: "+words.length);}
    }
    public static void main(String[] args) {
        new Counter();
    }}

But I don't want to count words whenever I click the button but in real-time so the values update each frame. Do I need to use multi-threading for this or it can be achieved without it?

You need to use DocumentListener on JTextArea instead of AstionListener on JButton.

void test() {
   JTextArea textArea = new JTextArea();

   textArea.getDocument().addDocumentListener(new DocumentListener() {
       @Override
       public void insertUpdate(DocumentEvent e) {
           recalculateWords();;
       }

       @Override
       public void removeUpdate(DocumentEvent e) {
           recalculateWords();
       }

       @Override
       public void changedUpdate(DocumentEvent e) {
           recalculateWords();
       }
   });
}

void recalculateWords() {
    //Use your code from actionPerfomed here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM