Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

java - How to update the JTextField when the variable value is changed?

I have two Java(.java) files. One has a JButton and JTextField and the other has a Thread. In first Java file, I have added an ActionListener to the JButton so that, when the button is pressed, a thread (object for 2nd .java file in created and thread is initiated) runs which modifies an integer variable continuously. How to display the value of that integer variable (of 2nd .java file) in the JTextField (of 1st .java file) ?

Detection.java

package sample;
public class Detection implements Runnable
{
    public String viewers;
    public int count;
    public void run() 
    {                         
        try 
        {
            while (true) 
            {
                // i have written code for displaying video.
                // and it say how many no. of people in the video 
                // the no of people is stored in a variable "count"

                viewers=""+count; //storing count as string so as to display in the JTextField
            }           
        }                
        catch (Exception e)
        {
            System.out.println("Exception: "+e);
        }
    }
}

UsrInterfac.java

//build using WindowBuilder eclipse juno

package sample;
import java.awt.EventQueue;    
import javax.swing.JFrame;   
import javax.swing.JButton;    
import javax.swing.JTextField;    
import java.awt.event.ActionListener;    
import java.awt.event.ActionEvent;    

public class UsrInterfac 
{    
    private JFrame frame;
    private JTextField textField;
    Detection dd = new Detection();
    Thread th = new Thread(dd);

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

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

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

        JButton btnStartThread = new JButton("Start Thread");
        btnStartThread.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent arg0) 
            {               
                th.start();                 
            }
        });
        btnStartThread.setBounds(59, 133, 117, 23);
        frame.getContentPane().add(btnStartThread);

        textField = new JTextField();
        textField.setBounds(270, 134, 104, 20);
        frame.getContentPane().add(textField);
        textField.setColumns(10);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Starting from the basics, while using Swing, it is always best to use LayoutManagers, which can make your work much more easier, in comparison to using Absolute Positioning. Whenever one needs to change something in the View from some another thread, it is always advisable to do that using EventQueue.invokeLater(...)/EventQueue.invokeAndWait(...).

This small sample program, might be able to help you get an idea, how to accomplish what you so desire :-)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ThreadCounter
{
    private CustomThread cThread;
    private JTextField tField;
    private JButton button;
    private int counter;

    public ThreadCounter()
    {
        counter = 0;
    }

    private void displayGUI()
    {
        JFrame frame = new JFrame("Thread Counter Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        tField = new JTextField(10);
        tField.setText("0");
        button = new JButton("Start");
        button.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                if (counter == 0)
                {
                    cThread = new CustomThread(tField);
                    cThread.setFlagValue(true);
                    cThread.start();
                    counter = 1;
                    button.setText("Stop");
                }
                else
                {
                    try
                    {
                        cThread.setFlagValue(false);
                        cThread.join();
                    }
                    catch(InterruptedException ie)
                    {
                        ie.printStackTrace();
                    }
                    counter = 0;
                    button.setText("Start");
                }
            }
        });

        contentPane.add(tField);
        contentPane.add(button);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new ThreadCounter().displayGUI();
            }
        });
    }
}

class CustomThread extends Thread
{
    private int changingVariable;
    private JTextField tField;
    private boolean flag = true;

    public CustomThread(JTextField tf)
    {
        changingVariable = 0;
        tField = tf;
    }   

    public void setFlagValue(boolean flag)
    {
        this.flag = flag;
    }

    @Override
    public void run()
    {
        while (flag)
        {
            EventQueue.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    tField.setText(
                        Integer.toString(
                            ++changingVariable));
                }
            });

            try
            {
                Thread.sleep(1000);
            }
            catch(InterruptedException ie)
            {
                ie.printStackTrace();
            }
        }
        System.out.println("I am OUT of WHILE");
    }    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...