如何使网络计数器值包含在我的主JButton目标中?我在做这样的事情:
Main.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) {
}
}
}
Process.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();
}
}
Network.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);
}
}
NetworkListener.java
package demo;
public interface NetworkListener
{
public void Registered();
}
发布于 2011-09-12 13:16:23
假设您想要更新显示计数器的某个组件,则不太清楚您希望如何查看计数器。
基本上,您将需要一个最终导致通知EDT上计数器更改的设置,然后您的ui侦听该更改并酌情更新组件。F.i。
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;
}
};
https://stackoverflow.com/questions/7379226
复制相似问题