Home > front end >  Java GUI Real Time Word Counter
Java GUI Real Time Word Counter

Time:12-11

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?

CodePudding user response:

You need to use a DocumentListener on the JTextArea instead of an ActionListener on a 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.
}
  • Related