不会用timer,参考很多例子还是搞不定,我想在程序里面每秒更新一下textfield的内容,先谢过大虾
package SM;
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
*/
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]);
}
//*********************************************
// 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);
}
package SM;
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
*/
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]);
}
//*********************************************
// 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);
}}
监听器里面的实现代码,一般是禁止使用Thead.sleep方法和IO操作的。
因为,该实现方法,会被图形界面的绘制线程所调用。
如果该实现方法长时间无法返回,则,用户界面就会处于僵死状态。
并且,Button的响应代码,只在触发事件的时候执行一次,不是无限循环执行的。推荐楼主,写一个线程的实现类,或者,使用Timer类填写执行代码,就可以了。