1

如何让网络计数器值包含在我的Main JButton 目标中?我正在做这样的事情:

主.java:

package demo;

import java.awt.BorderLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JWindow;

public class Main extends JWindow
{
    private static JButton goal = new JButton("old");
    private static JWindow j;
    private static Process application;

    public Main()
    {   
       this.setLayout (new BorderLayout ());
       this.setVisible(true);
       this.add(goal,BorderLayout.NORTH);
    }

    public static void main(String[] args)
    {
        j = new Main();
        j.setVisible(true);

        try {
            application = new Process();
            application.start();
            // <<<<< Here i want to see the counter, from network.java >>>>>
        } catch (Exception ex) {

        }
    }
}

进程.java

package demo;

import java.util.Vector;

public class Process extends Thread 
{
  public Network alert;          
  public Vector listenerList;
  private boolean running;

  public Process() throws Exception
  {
    listenerList = new Vector();
    alert = new Network(); 
    addNetworkListener(alert);

    this.running = true;
  }

  public void addNetworkListener(Network ls)
  {
    listenerList.addElement(ls);
  }

  public void run()
  {
    System.out.println("Starting..");  
    try {
      while(running)
      {
        System.out.println("running...");
        FireEvent();
      }
    } catch (Exception ex) {
      //
    }
  }

  private void FireEvent()
  {
     //System.exit(0);
     alert.Registered();
  }
}

网络.java

package demo;

public class Network implements NetworkListener 
{    
    public int  counter = 0 ;
    public void Registered() 
    {
        System.out.println("network: " + counter);
        counter++;
        if (counter>40) System.exit(0);
    }

}

网络监听器.java

package demo;

public interface NetworkListener 
{
    public void Registered();
}
4

1 回答 1

0

假设您要更新显示计数器的某些组件,不太清楚您希望如何查看计数器。

基本上,您将需要一个设置,最终导致通知EDT 上计数器的更改然后您的 ui 侦听该更改并根据需要更新组件。Fi

public class Network implements NetworkListener 
{    
    public int  counter = 0 ;
    public void registered() 
    {
        System.out.println("network: " + counter);
        counter++;
        SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                 fireCounterChanged( ... );
             }
        });
        if (counter>40) System.exit(0);
    }

    public void addChangeListener(...) {
         ....
    }

    public void removeChangeListener(...) {
         ....
    }
    private void fireCounterChanged(...) {
        // notify all listeners
    }  

}

// usage
ChangeListener l = new ChangeListener() {
       public void stateChanged(ChangeEvent e) {
           button.setText("counter: " + ((NetWork) e.getSource()).counter;
       }
}; 
于 2011-09-12T13:16:23.947 回答