简体   繁体   English

更新多个文本框Java GUI

[英]Updating Multiple Textbox Java GUI

I have an activity or form in which there is one text box called time here. 我有一个活动或表单,其中有一个称为时间的文本框。 As suggested by experts from this forum I am using runnable to update the TextBox while receiving the data from wifi. 正如该论坛的专家建议的那样,我在从wifi接收数据时使用runnable更新TextBox。

My doubt is what to do when I want to update multiple TextBox's. 我的疑问是当我想更新多个TextBox时该怎么做。 Should I use multiple blocks of runnables like 我应该使用多个可运行对象块吗

              time1.post(new Runnable() {
                @Override
                public void run() {
                    time2.setText(s1);
                }
              });

             time2.post(new Runnable() {
                @Override
                public void run() {
                    time2.setText(s2);
                }
              });

            time3.post(new Runnable() {
                @Override
                public void run() {
                    time3.setText(s2);
                }
              });

Or some other technique is there to update multiple TextBoxes? 还是有其他技术可以更新多个TextBox? My present code is like below. 我现在的代码如下。

package com.example.cdttiming;

public class MainActivity extends Activity
{
    EditText time;
    String s;
    Button button;
    byte[] buffer = new byte[65535];
    InetAddress ia = null;
     byte[] bmessage = new byte[1500];
     DatagramPacket dp = new DatagramPacket(bmessage, bmessage.length);
     MulticastSocket ms = null;
    @Override

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        time = (EditText) findViewById(R.id.et_time);
    try 
        {
        WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE); 
        WifiManager.MulticastLock multicastLock = wm.createMulticastLock("multicastLock");
        multicastLock.setReferenceCounted(true);        
        multicastLock.acquire();      

        ia = InetAddress.getByName("226.1.1.1");    
        try {
            ms = new MulticastSocket(4321);
            } catch (IOException e) {
            e.printStackTrace();
            }
        try {
            ms.joinGroup(ia);
            } catch (IOException e) {
            e.printStackTrace();
            }

        ms.setReuseAddress(true);

        }
           catch (UnknownHostException e)               {
                time.setText(e.getMessage());

            }
            catch (IOException e)                {
                time.setText(e.getMessage());
             }     
     }

    public void startProgress(View view) {
        Runnable runnable = new Runnable() {
          @Override
          public void run() {              
        while(true)             {
             try                 {
                // String str="This is test string";
                  ms.receive(dp);
                  s = new String(dp.getData(),0,dp.getLength()); 
                  char retval[] = s.toCharArray();
             }
             catch (UnknownHostException e)                 {
                 time.setText(e.getMessage());

                }
               catch (IOException e)                    {
                   time.setText(e.getMessage());
                }     

            ****////// My doubt is here if i have multple strings of data and multiple
            /// multiple textboxes to update then what to do ???****

             time.post(new Runnable() {
                @Override
                public void run() {
                    time.setText(s);

                }
              });
           }  // while
          }
        };
        new Thread(runnable).start();
      }

    @Override
     public boolean onCreateOptionsMenu(Menu menu)      {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }   
}

I suggest you only create one runnable and post it once on main thread like this : 我建议您只创建一个可运行对象,并将其发布到主线程上一次,如下所示:

      time1.post(new Runnable() {
        @Override
        public void run() {
            time2.setText(s1);
            time2.setText(s2);
            time3.setText(s3);
        }
      });

The need to create a runnable and to post it on the main thread handler of a view is only about running a piece of code on the UI thread. 创建可运行对象并将其发布到视图的主线程处理程序中的需要仅是关于在UI线程上运行一段代码。 No matter where you get the main thread handler reference from. 无论您从何处获取主线程处理程序引用。

you could also have created your how handler on main thread : 您也可以在主线程上创建how处理程序:

protected void onCreate(Bundle savedInstanceState)
{
      this.uiThrdHandler = new Handler();
}

then post a runnable using it : 然后使用它发布一个可运行的:

this.uiThrdHandler.post(new Runnable(){
        ...
});

Of course there is no need to create another handler but it's for demonstration purpose. 当然,无需创建其他处理程序,但这只是出于演示目的。

The Activity object has an utility method for that purpose : runOnUiThread Activity对象具有用于该目的的实用程序方法: runOnUiThread

Using it, it would be : 使用它,它将是:

  MainActivity.this.runOnUiThread (new Runnable() {
        @Override
        public void run() {
            time2.setText(s1);
            time2.setText(s2);
            time3.setText(s3);
        }
      });

But again, the result is the same. 但是同样,结果是一样的。

Your code is a bit confusing. 您的代码有点混乱。 In one case inside your primary while loop you are capturing the data, assigning it to a String variable s then using the text widget post() function and a Runnable to set the EditText widget to that value. 在主内一个案例while循环要捕获的数据,将其分配给一个字符串变量s然后使用文本组件后()函数和一个Runnable的EditText小部件设置为该值。 But inside that same while loop you have exception handlers that simply set the same EditText widget directly. 但是在同一个while循环中,您具有异常处理程序,它们可以直接直接设置相同的EditText小部件。 Your code also looks like you could potentially lose messages if the while loop resets the value of s before the timer loop has a chance to fire the set text call. 如果while循环在计时器循环有机会触发设置的文本调用之前重置s的值,您的代码也看起来可能会丢失消息。

It appears you are trying to create some form of real-time system and need the primary while loop to continually process, and display data as it becomes available. 看来您正在尝试创建某种形式的实时系统,并且需要主while循环来连续处理并在可用时显示数据。 Now you have 3 different consumers (text widgets), but you didn't mention if you also have 3 different sources of messages or is there still only one main processing loop and some form of selector will decide which text widget gets the message? 现在,您有3个不同的使用者(文本小部件),但是您没有提到是否还有3个不同的消息源,还是仍然只有一个主处理循环,并且某种形式的选择器将决定哪个文本小部件获取消息?

Were I building something along these lines, I would probably use a messaging system and follow the producer-consumer model. 如果我按照这些思路进行构建,可能会使用消息传递系统并遵循生产者-消费者模型。 When text was received, I would have the primary processing loop push a simple 2-field message onto a queue that contained a reference to the text widget and a reference to the data string. 当接收到文本时,我将使主要处理循环将一个简单的2字段消息推送到队列中,该队列包含对文本小部件的引用和对数据字符串的引用。 Because Strings are immutable in Java, once the message object had its own copy of the text, any changes to s would not affect the message. 因为字符串在Java中是不可变的,所以一旦消息对象拥有自己的文本副本,对s的任何更改都不会影响消息。

Then, I would have a second thread running in the background that consumes the message queue. 然后,我将在后台运行另一个消耗消息队列的线程。 It would pull the message off the queue, construct a post call to the target text widget with the message data, fire it off, then go back to get the next message. 它将使消息脱离队列,使用消息数据构造对目标文本小部件的调用,将其触发,然后返回以获取下一条消息。

By going this route you separate the data processing thread from the UI update processing and would not need to worry about how many text widgets or other widgets you need updated. 通过这种方法,您可以将数据处理线程与UI更新处理分开,而无需担心需要更新多少个文本小部件或其他小部件。 If you ever need to add others you only need to worry about the new widgets being known to the code that creates the update messages. 如果您需要添加其他组件,则只需担心创建更新消息的代码会知道新的窗口小部件。 The thread doing the widget update doesn't know how many widgets you have, it simply uses the one referenced in the update message object that the message creator said to use. 进行小部件更新的线程不知道您有多少个小部件,它仅使用消息创建者所说的在更新消息对象中引用的小部件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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