如何在更改变量值时更新JTextField? [英] How to update the JTextField when the variable value is changed?

查看:109
本文介绍了如何在更改变量值时更新JTextField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Java(.java)文件。一个有 JButton JTextField ,另一个有一个 Thread 。在第一个 Java文件中,我已将 ActionListener 添加到 JButton 这样,当按下按钮时,一个线程(创建的第二个.java文件的对象和启动的线程)运行,它会连续修改整数变量。如何在 JTextField (第一个.java文件)中显示该整数变量(第二个.java文件)的值?

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

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

UsrInterfac.java

//使用WindowBuilder构建eclipse juno

//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);
    }
}


推荐答案

开始从基础知识来看,使用Swing时,最好使用 LayoutManagers ,与使用绝对定位相比,可以使您的工作更轻松。
每当需要从另一个线程更改 View 中的某些内容时,始终建议使用 EventQueue.invokeLater(。 ..)/ EventQueue.invokeAndWait(...)

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");
    }    
}

这篇关于如何在更改变量值时更新JTextField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆