目前这个code只会显示最后的结果,我希望可以每隔一秒更新一下textField的内容,我试过用timer但总是出错,求人帮忙改改,先谢
------------------------------------------------------------------------------------------------------------
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.*;public class Simulation extends JFrame implements ActionListener{ /**
* @param args
*/
// Timer timer; private static final int WIDTH=1120;
private static final int HEIGHT=600;
private JButton startBtn;
private JTextField[] till=new JTextField[5];
private JTextField MAXCUSTOMERS,MAXTILLS,MAXITEMS,ROUNDSTOSIMULATE,ARRIVALRATE;
//************************************************************
// User specified fields to be input at the simulation start *
//************************************************************
private int MAX_CUSTOMERS; // Maximum number of customers.
private int MAX_TILLS; // The number of checkout tills.
private int MAX_ITEMS; // The maximum number of items.
private int ROUNDS_TO_SIMULATE; // Number of simulation rounds during which
// new customers can arrive.
private double ARRIVAL_RATE; // Should be a value between 0.0 and 1.0,
// higher value == more frequent arrivals.
//***********************************************************
// The following fields allow a user to specify statistical *
// information that should be output. *
//***********************************************************
private int UPDATE_STATS=1; // Show till status every
// UPDATE_STATS iterations
private boolean FINAL_ONLY=false; // Only show final customer records
// do not show statistics every iteration.
private boolean AVERAGE_MAX_ONLY=false; // Only show average and maximum values for
// Queue Lengths, Service Times, etc.
//************************************************************
// These fields hold various statistics that can be collated *
// as a simulation procedes. *
//************************************************************
private int customers_left=0; // The customers remaining in queues
private int customers_through=0; // The total number of customers.
private int longest_queue_length =0;
private int longest_queue;
//****************************************************
// Fields associated with the Simulation Process *
//****************************************************
private Queue[] CheckOutQueues; // The Queue at each Checkout;
private int[] TimeLeftAtTill; // Time remaining before a till is free.
private Customer[] CustomerStats; // Records Customer data.
int just_served; // To index CustomerStats[]
int put_on_queue; // To index CheckOutQueues[]
int on_round_number =0; // Current simulation round
int firstinQ; // Used in updating Queue/Customer
int nextinQ; //
Integer CustomerIndex; // Need Integer to store int index on Queue
String[] x=new String[5];
public Simulation(){
setSize(WIDTH,HEIGHT);
Container contentPane=getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new FlowLayout());
add(new Label(" "));
add(new Label("New York Mart "));
startBtn=new JButton("Start");
startBtn.addActionListener(this);
contentPane.add(startBtn);
add(new Label(" "));
add(new Label("Maximum Number of Customers:"));
MAXCUSTOMERS=new JTextField(5);
MAXCUSTOMERS.setText("");
contentPane.add(MAXCUSTOMERS);
add(new Label("Maximum Number of Tills:"));
MAXTILLS=new JTextField(5);
MAXTILLS.setText("");
contentPane.add(MAXTILLS);
add(new Label("Maximum Number of Items:"));
MAXITEMS=new JTextField(5);
MAXITEMS.setText("");
contentPane.add(MAXITEMS);
add(new Label("Rounds to Simulate:"));
ROUNDSTOSIMULATE=new JTextField(5);
ROUNDSTOSIMULATE.setText("");
contentPane.add(ROUNDSTOSIMULATE);
add(new Label("Arrival Rate(0~1):"));
ARRIVALRATE=new JTextField(5);
ARRIVALRATE.setText("");
contentPane.add(ARRIVALRATE);
add(new Label("Till #0"));
till[0]=new JTextField(100);
till[0].setText("");
contentPane.add(till[0]);
add(new Label("Till #1"));
till[1]=new JTextField(100);
till[1].setText("");
contentPane.add(till[1]);
add(new Label("Till #2"));
till[2]=new JTextField(100);
till[2].setText("");
contentPane.add(till[2]);
add(new Label("Till #3"));
till[3]=new JTextField(100);
till[3].setText("");
contentPane.add(till[3]);
add(new Label("Till #4"));
till[4]=new JTextField(100);
till[4].setText("");
contentPane.add(till[4]);
// timer = new Timer(1000,this);
// timer.start(); }
//*********************************************
// Initiate Simulation Structures *
//*********************************************
private void StartUpQueues()
{
CheckOutQueues = new Queue[MAX_TILLS];
TimeLeftAtTill = new int[MAX_TILLS];
for (int i=0; i<MAX_TILLS; i++)
CheckOutQueues[i] = new Queue();
}
//*********************************************
// Simulation over when all Qs empty and *
// the required number of rounds is over. *
//*********************************************
private boolean AllCustomersServed()
{
boolean ok=true;
int till_check =0;
while ((ok) && (till_check < MAX_TILLS))
{
ok = ( (ok) && (CheckOutQueues[till_check].QIsEmpty()) );
till_check++;
};
return ok;
}
//**********************************************************
// The following 4 methods output details of the customer *
// and checkout queues as the simulation procedes. *
//**********************************************************
private void ShowServedCustomer( int qnum, int cnum )
{
System.out.println("Customer at till "+qnum+" is Customer "+cnum+
" who arrived at "+ CustomerStats[cnum].get_arrived()+" and is buying "+
CustomerStats[cnum].get_service_time()+" items. "+
" Time left to wait is "+ TimeLeftAtTill[qnum]);
}
private void OutputCheckOutStats( int after_round )
{
int firstinQ;
System.out.println("Check Out Tills after "+after_round+" rounds");
System.out.println("**********************************************");
for (int i=0; i<MAX_TILLS; i++)
{
System.out.print("Check Out Queue "+i+": ");
System.out.println(" Length: "+CheckOutQueues[i].GetWaiting() );
if (!CheckOutQueues[i].QIsEmpty())
{
firstinQ =
Integer.valueOf(CheckOutQueues[i].GetFirstInQ().toString()).intValue();
ShowServedCustomer(i,firstinQ);
};
};
System.out.println("**********************************************");
System.out.println("Customers seen: "+customers_through);
System.out.println("Customers remaining: "+customers_left);
System.out.println("**********************************************");
}
//**********************************************************
private void OutputCustomerStats()
{
System.out.println("Customer Records after Completion");
System.out.println("**********************************************");
for (int i=0; i<customers_through; i++)
{
System.out.print("Customer "+i+": Arrived: "+
CustomerStats[i].get_arrived());
System.out.print(" Left: "+
CustomerStats[i].get_depart());
System.out.print(" Bought: "+
CustomerStats[i].get_service_time()+
" items");
System.out.println(" at till: "+
CustomerStats[i].get_checkout());
};
}
//***********************************************************************
private void OutputAverageMaxStats( int total_time )
{
int longest_wait=0;
int longest_waiting=0;
int total_waiting_time=0;
int temp_wait;
double average_wait;
System.out.println(" Average and Maxima Statistics");
System.out.println("**********************************************");
System.out.println("Total customers dealt with: "+customers_through);
System.out.println("Total time to complete serving: "+ total_time);
System.out.println("Longest queue had length "+
longest_queue_length+ " at till "+
longest_queue);
for (int i=0; i<customers_through; i++)
{
temp_wait = CustomerStats[i].get_depart()-
CustomerStats[i].get_arrived();
total_waiting_time = total_waiting_time+temp_wait;
if (temp_wait > longest_wait)
{
longest_wait = temp_wait; longest_waiting=i;
};
};
average_wait = total_waiting_time/customers_through;
System.out.println("Longest wait was "+
longest_wait+ " for customer "+
longest_waiting + " in check out queue "+
CustomerStats[longest_waiting].get_checkout());
System.out.println("Average waiting time was "+average_wait);
}
------------------------------------------------------------------------------------------------------------
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.*;public class Simulation extends JFrame implements ActionListener{ /**
* @param args
*/
// Timer timer; private static final int WIDTH=1120;
private static final int HEIGHT=600;
private JButton startBtn;
private JTextField[] till=new JTextField[5];
private JTextField MAXCUSTOMERS,MAXTILLS,MAXITEMS,ROUNDSTOSIMULATE,ARRIVALRATE;
//************************************************************
// User specified fields to be input at the simulation start *
//************************************************************
private int MAX_CUSTOMERS; // Maximum number of customers.
private int MAX_TILLS; // The number of checkout tills.
private int MAX_ITEMS; // The maximum number of items.
private int ROUNDS_TO_SIMULATE; // Number of simulation rounds during which
// new customers can arrive.
private double ARRIVAL_RATE; // Should be a value between 0.0 and 1.0,
// higher value == more frequent arrivals.
//***********************************************************
// The following fields allow a user to specify statistical *
// information that should be output. *
//***********************************************************
private int UPDATE_STATS=1; // Show till status every
// UPDATE_STATS iterations
private boolean FINAL_ONLY=false; // Only show final customer records
// do not show statistics every iteration.
private boolean AVERAGE_MAX_ONLY=false; // Only show average and maximum values for
// Queue Lengths, Service Times, etc.
//************************************************************
// These fields hold various statistics that can be collated *
// as a simulation procedes. *
//************************************************************
private int customers_left=0; // The customers remaining in queues
private int customers_through=0; // The total number of customers.
private int longest_queue_length =0;
private int longest_queue;
//****************************************************
// Fields associated with the Simulation Process *
//****************************************************
private Queue[] CheckOutQueues; // The Queue at each Checkout;
private int[] TimeLeftAtTill; // Time remaining before a till is free.
private Customer[] CustomerStats; // Records Customer data.
int just_served; // To index CustomerStats[]
int put_on_queue; // To index CheckOutQueues[]
int on_round_number =0; // Current simulation round
int firstinQ; // Used in updating Queue/Customer
int nextinQ; //
Integer CustomerIndex; // Need Integer to store int index on Queue
String[] x=new String[5];
public Simulation(){
setSize(WIDTH,HEIGHT);
Container contentPane=getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new FlowLayout());
add(new Label(" "));
add(new Label("New York Mart "));
startBtn=new JButton("Start");
startBtn.addActionListener(this);
contentPane.add(startBtn);
add(new Label(" "));
add(new Label("Maximum Number of Customers:"));
MAXCUSTOMERS=new JTextField(5);
MAXCUSTOMERS.setText("");
contentPane.add(MAXCUSTOMERS);
add(new Label("Maximum Number of Tills:"));
MAXTILLS=new JTextField(5);
MAXTILLS.setText("");
contentPane.add(MAXTILLS);
add(new Label("Maximum Number of Items:"));
MAXITEMS=new JTextField(5);
MAXITEMS.setText("");
contentPane.add(MAXITEMS);
add(new Label("Rounds to Simulate:"));
ROUNDSTOSIMULATE=new JTextField(5);
ROUNDSTOSIMULATE.setText("");
contentPane.add(ROUNDSTOSIMULATE);
add(new Label("Arrival Rate(0~1):"));
ARRIVALRATE=new JTextField(5);
ARRIVALRATE.setText("");
contentPane.add(ARRIVALRATE);
add(new Label("Till #0"));
till[0]=new JTextField(100);
till[0].setText("");
contentPane.add(till[0]);
add(new Label("Till #1"));
till[1]=new JTextField(100);
till[1].setText("");
contentPane.add(till[1]);
add(new Label("Till #2"));
till[2]=new JTextField(100);
till[2].setText("");
contentPane.add(till[2]);
add(new Label("Till #3"));
till[3]=new JTextField(100);
till[3].setText("");
contentPane.add(till[3]);
add(new Label("Till #4"));
till[4]=new JTextField(100);
till[4].setText("");
contentPane.add(till[4]);
// timer = new Timer(1000,this);
// timer.start(); }
//*********************************************
// Initiate Simulation Structures *
//*********************************************
private void StartUpQueues()
{
CheckOutQueues = new Queue[MAX_TILLS];
TimeLeftAtTill = new int[MAX_TILLS];
for (int i=0; i<MAX_TILLS; i++)
CheckOutQueues[i] = new Queue();
}
//*********************************************
// Simulation over when all Qs empty and *
// the required number of rounds is over. *
//*********************************************
private boolean AllCustomersServed()
{
boolean ok=true;
int till_check =0;
while ((ok) && (till_check < MAX_TILLS))
{
ok = ( (ok) && (CheckOutQueues[till_check].QIsEmpty()) );
till_check++;
};
return ok;
}
//**********************************************************
// The following 4 methods output details of the customer *
// and checkout queues as the simulation procedes. *
//**********************************************************
private void ShowServedCustomer( int qnum, int cnum )
{
System.out.println("Customer at till "+qnum+" is Customer "+cnum+
" who arrived at "+ CustomerStats[cnum].get_arrived()+" and is buying "+
CustomerStats[cnum].get_service_time()+" items. "+
" Time left to wait is "+ TimeLeftAtTill[qnum]);
}
private void OutputCheckOutStats( int after_round )
{
int firstinQ;
System.out.println("Check Out Tills after "+after_round+" rounds");
System.out.println("**********************************************");
for (int i=0; i<MAX_TILLS; i++)
{
System.out.print("Check Out Queue "+i+": ");
System.out.println(" Length: "+CheckOutQueues[i].GetWaiting() );
if (!CheckOutQueues[i].QIsEmpty())
{
firstinQ =
Integer.valueOf(CheckOutQueues[i].GetFirstInQ().toString()).intValue();
ShowServedCustomer(i,firstinQ);
};
};
System.out.println("**********************************************");
System.out.println("Customers seen: "+customers_through);
System.out.println("Customers remaining: "+customers_left);
System.out.println("**********************************************");
}
//**********************************************************
private void OutputCustomerStats()
{
System.out.println("Customer Records after Completion");
System.out.println("**********************************************");
for (int i=0; i<customers_through; i++)
{
System.out.print("Customer "+i+": Arrived: "+
CustomerStats[i].get_arrived());
System.out.print(" Left: "+
CustomerStats[i].get_depart());
System.out.print(" Bought: "+
CustomerStats[i].get_service_time()+
" items");
System.out.println(" at till: "+
CustomerStats[i].get_checkout());
};
}
//***********************************************************************
private void OutputAverageMaxStats( int total_time )
{
int longest_wait=0;
int longest_waiting=0;
int total_waiting_time=0;
int temp_wait;
double average_wait;
System.out.println(" Average and Maxima Statistics");
System.out.println("**********************************************");
System.out.println("Total customers dealt with: "+customers_through);
System.out.println("Total time to complete serving: "+ total_time);
System.out.println("Longest queue had length "+
longest_queue_length+ " at till "+
longest_queue);
for (int i=0; i<customers_through; i++)
{
temp_wait = CustomerStats[i].get_depart()-
CustomerStats[i].get_arrived();
total_waiting_time = total_waiting_time+temp_wait;
if (temp_wait > longest_wait)
{
longest_wait = temp_wait; longest_waiting=i;
};
};
average_wait = total_waiting_time/customers_through;
System.out.println("Longest wait was "+
longest_wait+ " for customer "+
longest_waiting + " in check out queue "+
CustomerStats[longest_waiting].get_checkout());
System.out.println("Average waiting time was "+average_wait);
}
// Select a Queue: A simple `greedy' method is used in which any new *
// customer is added to the current shortest queue *
// To compare different strategies, all that is needed is to replace *
// this method with an alternative. *
//***********************************************************************
private int ChooseQueueToJoin ( Queue[] CheckOuts )
{
int shortest_so_far =0;
for (int i=1; i<MAX_TILLS; i++)
{
if (CheckOuts[i].GetWaiting() < CheckOuts[shortest_so_far].GetWaiting() )
shortest_so_far =i;
};
return shortest_so_far;
}
//**********************************************************************//
// The number of items bought by a new customer is randomly chosen to //
// to be a value between 1 and MAX_ITEMS. //
//**********************************************************************//
private int NumberofItems()
{
return 1+(int) Math.rint( (MAX_ITEMS-1)*Math.random() );
}
private void GuiEnqueue(){
x[put_on_queue]+="Customer"+customers_through;
till[put_on_queue].setText(x[put_on_queue]);
/*try { UIManager.setLookAndFeel(UIManager. getSystemLookAndFeelClassName () );
}
catch ( Exception e ) {}
int time = 1;
while(true) {
time = Integer.parseInt( JOptionPane.showInputDialog ( "Enter time in seconds" ));
break;
}
time *=1000;
try {
Thread.sleep(time);
till[put_on_queue].setText(x[put_on_queue]);
} catch (Exception e) {}*/
} public void actionPerformed(ActionEvent f) {
// TODO Auto-generated method stub
String actionCommand=f.getActionCommand();
//Container contentPane=getContentPane();
MAX_CUSTOMERS=Integer.parseInt(MAXCUSTOMERS.getText());
MAX_TILLS=Integer.parseInt(MAXTILLS.getText());
MAX_ITEMS=Integer.parseInt(MAXITEMS.getText());
ROUNDS_TO_SIMULATE=Integer.parseInt(ROUNDSTOSIMULATE.getText());
ARRIVAL_RATE=Double.parseDouble(ARRIVALRATE.getText());
if (actionCommand.equals("Start")){
StartUpQueues(); // Initiate Queues, Tills
CustomerStats = new Customer[MAX_CUSTOMERS]; // And customer records.
//************************************************************
// Main simulation loop: Continues while customers remain *
// or the number of rounds is not completed. *
//************************************************************
/*try { UIManager.setLookAndFeel(UIManager. getSystemLookAndFeelClassName () );
}
catch ( Exception e ) {}
int time = 0;
while(true) {
time = 1;
break;
}
time *=1000;*/
while ( (!AllCustomersServed()) ||
(on_round_number < ROUNDS_TO_SIMULATE) )
{
on_round_number++; // Next simulation round;
//**********************************************
// Update the Status of each CheckOut Queue *
//**********************************************
for (int till=0; till<MAX_TILLS; till++)
{
//*****************************************************
// If current till being inspected has a non-empty Q *
// then find out the index of the Customer referenced *
// and decrease the time left until this till is free *
//*****************************************************
if (!CheckOutQueues[till].QIsEmpty())
{
firstinQ =
Integer.valueOf(CheckOutQueues[till].GetFirstInQ().toString()).intValue();
TimeLeftAtTill[till]--;
//***************************************************
// See if this customer has now been served and, if *
// so update the customer records and queue. *
//***************************************************
if (TimeLeftAtTill[till] < 1)
{
// Note the departure time.
CustomerStats[firstinQ].set_depart(on_round_number);
CheckOutQueues[till].removeQ(); // Remove customer from queue.
customers_left--; // now have one less customer.
//*****************************************************
// If any customer left, serve the next in this Queue *
//*****************************************************
if (!CheckOutQueues[till].QIsEmpty())
{
nextinQ =
Integer.valueOf((CheckOutQueues[till].GetFirstInQ()).toString()).intValue();
TimeLeftAtTill[till]=CustomerStats[nextinQ].get_service_time();
};
};
};
};
//*************************************************************
// Randomly decide (based on the given ARRIVAL_RATE) *
// whether a new customer has appeared. If so, then *
// initiate a new Customer record and choose a CheckOutQueue *
//*************************************************************
if ( (Math.random()<ARRIVAL_RATE) &&
(customers_through<MAX_CUSTOMERS) &&
(on_round_number < ROUNDS_TO_SIMULATE) )
{
CustomerStats[customers_through] = new Customer();
CustomerStats[customers_through].set_arrived(on_round_number);
CustomerStats[customers_through].set_service_time(NumberofItems());
CustomerStats[customers_through].set_id(customers_through);
put_on_queue = ChooseQueueToJoin(CheckOutQueues);
//******************************************************
// If the CheckOutQueue chosen is empty, then the new *
// customer will be served at once. *
//******************************************************
if ( CheckOutQueues[put_on_queue].QIsEmpty() )
TimeLeftAtTill[put_on_queue] =
CustomerStats[customers_through].get_service_time();
CustomerStats[customers_through].set_checkout(put_on_queue);
CustomerIndex = new Integer(customers_through);
CheckOutQueues[put_on_queue].insertQ(CustomerIndex);
GuiEnqueue();
/*try {
Thread.sleep(time);
} catch (Exception d) {}*/
//*******************************************************************
// Test if the queue length is greater than any seen before, and *
// update queue length statistics accordingly. *
//*******************************************************************
if (CheckOutQueues[put_on_queue].GetWaiting() > longest_queue_length)
{
longest_queue_length = CheckOutQueues[put_on_queue].GetWaiting();
longest_queue = put_on_queue;
};
customers_left++; // One more customer in the system.
customers_through++; // One more customer seen.
};
//*****************************************************************
// Output Statistics as required *
//*****************************************************************
if ( (on_round_number%UPDATE_STATS==0) &&
(!FINAL_ONLY) &&
(!AVERAGE_MAX_ONLY) )
OutputCheckOutStats(on_round_number);
};
}
//*************************************************************
// Simulation rounds completed, so output statistcal info. *
//*************************************************************
if (AVERAGE_MAX_ONLY)
OutputAverageMaxStats(on_round_number);
else
{
OutputCustomerStats();
OutputAverageMaxStats(on_round_number);
};
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Simulation gui=new Simulation();
gui.setVisible(true);
}}
{
//*****************************************************
// A Queue is implemented as a linked sequence of *
// QCell. A QCell includes 2 fields: one the item *
// in the Queue (QItem); the other a link to the next *
// Queue cell. *
//*****************************************************
// QCell class only known to the Queue class itself. *
//*****************************************************
private class QCell
{
//
// QCell Fields
//
private Object QItem;
private QCell QLink;
//
// QCell Constructor
//
private QCell(Object head, QCell NextInQ)
{
QItem = head; QLink=NextInQ;
}
}
//******************************************************
// Queue Fields *
//******************************************************
// First: The QCell that contains the item at the *
// head of the Queue. *
// *
// Rest: Indicates the Queue following the first *
// Queue member. *
// Last: The most recently added Queue Item *
// Waiting: The number of items in this Queue *
//******************************************************
private QCell First;
private QCell Rest;
private QCell Last;
private int Waiting;
//******************************************************
// Queue Constructor - Initiates the Empty Queue *
//******************************************************
public Queue()
{
First = null;
Rest = null;
Last = null;
Waiting=0;
}
//******************************************************
// Queue Instance Methods *
//******************************************************
//
// Test if this Queue Is Empty
//
public boolean QIsEmpty()
{
return (Waiting==0);
};
//*****************************************************
// Return the length of this Queue *
//*****************************************************
public int GetWaiting()
{
return Waiting;
}
//************************************************************
// Add a new Object to the end of this Queue; *
// The new item is added in such a way that in traversing *
// this Queue, the item will be the Last one found. Further *
// additions will be appended after this. *
//************************************************************
public void insertQ ( Object EndofQ )
{
QCell temp;
//**********************************************************
// If this Queue is empty then the First and Last Queue *
// Cells are identical. *
//**********************************************************
if (QIsEmpty())
{
Last = new QCell(EndofQ,Last);
First = Last;
Rest = First.QLink;;
Waiting=1;
}
else
{
Last.QLink = new QCell(EndofQ,Last.QLink); // The last item is the one being added.
Last = Last.QLink;
Waiting++; // Increase Length of this Queue.
};
}
//***************************************************************
// Remove the First item (the item at the head of) this Queue *
//***************************************************************
public void removeQ()
{
if (Waiting<=1) // Will leave the empty Queue
{ // after removal.
First = null; Last=null; Rest=null;
Waiting=0;
}
else
{
First = First.QLink; // Find the `new' head of the Queue.
Waiting--; // One fewer item in Queue.
if (Waiting==1) // Deal with the case that there's
{ // exactly one item left in this Queue.
Last = First;
Rest = null;
}
else
Rest = First.QLink; // If more than one; reset Rest of Queue
}; // indicator.
}
//****************************************************************
// Return the First item (the item at the head of) this Queue *
// The Queue structure is left unchanged. *
//****************************************************************
public Object GetFirstInQ()
{
if (!(Waiting==0)) // If there's anything to return
return First.QItem; // then return it.
else
return null; // otherwise return a null reference.
}
//*****************************************************************
// Return the remainder (all but the first item) of this Queue *
// The Queue structure is left unchanged. *
//*****************************************************************
public Queue GetRestOfQ()
{
Queue temporary= new Queue();
temporary.First=First;
temporary.Rest=Rest;
temporary.Last=Last;
temporary.Waiting = Waiting;
temporary.removeQ();
return temporary;
};
//***********************************************************
// Return a String representing the contents of this Queue *
// in a form that is suitable to print out. *
//***********************************************************
public String toString()
{
String res = new String();
Queue temporary = new Queue();
temporary.First = First;
temporary.Rest = Rest;
temporary.Last = Last;
temporary.Waiting=Waiting;
while (!temporary.QIsEmpty())
{
res +=(temporary.GetFirstInQ()).toString()+"\n";
temporary = temporary.GetRestOfQ();
};
return res;
}
}
---------------------------------------------------------------------------
public class Customer
{
//****************************************
// Class Fields *
//****************************************
private int client_id; // Customer number
private int service_time; // Number of purchases
private int arrival_time; // Time of arrival (in Queue)
private int departure_time; // Time of departure (from checkout area)
private int checkout_till_number;// Check out till queue assigned to.
//*******************************************************************
// The Class Methods simply instantiate and return the field values *
//*******************************************************************
public void set_id(int id)
{ client_id = id; }
//
public void set_service_time(int time)
{ service_time = time; }
//
public void set_arrived(int time)
{ arrival_time = time; }
//
public void set_depart(int time)
{ departure_time = time; }
//
public void set_checkout(int till_number)
{ checkout_till_number = till_number; }
//
public int get_id()
{ return client_id; }
//
public int get_service_time()
{ return service_time ; }
//
public int get_arrived()
{ return arrival_time ; }
//
public int get_depart()
{ return departure_time ; }
//
public int get_checkout()
{ return checkout_till_number; }
}
public void run(){
while(true){
this.jframe.tfield.setText("hello");
try{
Thread.sleep(1000);
}catch(InterruptedException ex){
System.out.println("update textfile fail.");
}
}
}this.jframe是你的窗口对象,可以在线程类的构造方法中传入
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField; public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Demo frame = new Demo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} public Demo() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 300, 200);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
textField = new JTextField();
contentPane.add(textField);
textField.setColumns(10);
textField.setText("sqq");
JButton button = new JButton("New button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Update(textField).start();
}
});
contentPane.add(button);
}
class Update extends Thread{
JTextField textField;
public Update(JTextField textField){
this.textField = textField;
} @Override
public void run() {
int i = 0;
while (true) {
System.out.println(i);
textField.setText(i+"");
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}