简体   繁体   中英

SwingWorker process() doesn't update JTextArea in real time

I tried many solutions provided online, but still not work. I am creating a JAR and hope the text could be update in JTextArea in real time. But the text only append to textarea after finish the program.

My UI:

package Test;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import Test.SearchForWorker;

import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import java.awt.SystemColor;
import java.awt.Font;

public class TestTesr {

    private JFrame frame;
    private JTextField textField;
    private JTextArea console;
    private int input;

    public int getInput() {
        return input;
    }

    public void setInput(int input) {
        this.input = input;
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TestTesr window = new TestTesr();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public TestTesr() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 537, 360);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JPanel panel = new JPanel();
        panel.setBounds(0, 0, 233, 338);
        frame.getContentPane().add(panel);
        panel.setLayout(null);

        textField = new JTextField();
        textField.setBounds(5, 6, 130, 26);
        panel.add(textField);
        textField.setColumns(10);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(233, 6, 298, 326);
        frame.getContentPane().add(scrollPane);

        console = new JTextArea();
        console.setEditable(false);
        scrollPane.setViewportView(console);

        JButton btnNewButton = new JButton("Submit");
        btnNewButton.setBounds(140, 5, 88, 29);

        panel.add(btnNewButton);

        JLabel show = new JLabel("");
        show.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
        show.setForeground(SystemColor.textHighlight);
        show.setBounds(49, 115, 100, 53);
        panel.add(show);

        btnNewButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.out.print("Data Submitted");
                new SearchForWorker("Data Submitted", console).execute();
                ;

                String y = textField.getText();
                int g = Integer.parseInt(y);
                setInput(g);

                for (int u = 1; u <= 10; u++) {

                    try {
                        Thread.sleep(3000);
                    } catch (Exception q) {
                        System.out.println("Error occur for program time break" + q.toString());
                    }
                    g++;

                    new SearchForWorker("Inout plus " + u + " is :" + g, console).execute();
                    ;
                }

            }
        });
    }

}

SwingWorker:

package Test;

import java.awt.Color;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

public class SearchForWorker extends SwingWorker<String, String> {
    private final String display;
    private final JTextArea messageTextArea;
    TestTesr test = new TestTesr();

    SearchForWorker(final String output, final JTextArea area) {
        // initialize
        this.display = output;
        this.messageTextArea = area;
    }

    @Override
    protected String doInBackground() throws InterruptedException {
        System.out.println("Inside do in background for: "+display);
        publish(display);
        return display;
    }

    protected void done() {

    }

    @Override
    protected void process(List<String> showText){
        System.out.println("ShowText is: "+showText.toString());
        messageTextArea.append(showText.toString());
        messageTextArea.append("\n");
    }


}

after more than 3 years it might be thoroughly useless but isn't it what you wanted one day:

SwingWorker that worked for me

import java.util.List;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

public class SearchForWorker extends SwingWorker<String, String> {
    private int display;
    private final JTextArea messageTextArea;
    TestTesr test = new TestTesr();

    SearchForWorker(final String output, final JTextArea area) {
        // initialize
        this.display = Integer.parseInt(output);
        this.messageTextArea = area;
    }

    @Override
    protected String doInBackground() throws InterruptedException {
        System.out.println("Inside do in background for: " + display);
        // publish(display);
        int n = display;
        for (int u = 1; u <= 10; u++) {
            n++;
            publish(String.valueOf(n));
            test.panel.updateUI();

            try {
                Thread.sleep(100);
            } catch (Exception q) {
                System.out.println("Error occur for program time break" + q.toString());
            }
        }
        return String.valueOf(n);
    }

    @Override
    protected void process(List<String> showText) {
        System.out.println("ShowText is: " + showText.toString());
        messageTextArea.append("Inout plus " + showText + " is :" + showText.toString());
        messageTextArea.append("\n");
    }

    protected void done() {
        System.out.println("job Done!");
    }

}

and the UI with a little bit of change

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class TestTesr {

    private JFrame frame;
    private JTextField textField;
    private JTextArea console;
    protected JPanel panel;
    private int input;
    SearchForWorker sfw;

    public int getInput() {
        return input;
    }

    public void setInput(int input) {
        this.input = input;
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TestTesr window = new TestTesr();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public TestTesr() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 537, 360);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        panel = new JPanel();
        panel.setBounds(0, 0, 233, 338);
        frame.getContentPane().add(panel);
        panel.setLayout(null);

        textField = new JTextField();
        textField.setBounds(5, 6, 130, 26);
        panel.add(textField);
        textField.setColumns(10);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(233, 6, 298, 326);
        frame.getContentPane().add(scrollPane);

        console = new JTextArea();
        console.setEditable(false);
        scrollPane.setViewportView(console);

        JButton btnNewButton = new JButton("Submit");
        btnNewButton.setBounds(140, 5, 88, 29);

        panel.add(btnNewButton);

        JLabel show = new JLabel("");
        show.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
        show.setForeground(SystemColor.textHighlight);
        show.setBounds(49, 115, 100, 53);
        panel.add(show);

        btnNewButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.out.print("Data Submitted\n");
                console.append("Data Submitted\n");
                String y = textField.getText();
                int g = Integer.parseInt(y);
                setInput(g);

                try {
                    Thread.sleep(100);
                } catch (Exception q) {
                    System.out.println("Error occur for program time break" + q.toString());
                }
                g++;

                sfw = new SearchForWorker(String.valueOf(g), console);
                sfw.execute();

            }
        });
    }
}

some stuff is not exactly like what you have used in the original code like objects visibility. do some changes if you want.

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