📄 bank.java
字号:
import java.awt.*;
import java.awt.event.*;
public class Bank extends Frame implements ActionListener
{
//GUI component
private Label status = new Label("Transfers completed: 0");
private TextArea display = new TextArea();
private Button show = new Button("show accounts");
private Button start = new Button("restart");
private Button stop = new Button("stop");
//--end
protected final static int NUM_ACCOUNTS = 8;
private final static int WASTE_TIME = 1;
private int accounts[] = new int[NUM_ACCOUNTS];
private Customer customer[] = new Customer[NUM_ACCOUNTS];
private int counter = 0;
public Bank()
{
super("mystery money");
Panel buttons = new Panel();
buttons.setLayout(new FlowLayout());
buttons.add(show);
show.addActionListener(this);
buttons.add(start);
start.addActionListener(this);
buttons.add(stop);
stop.addActionListener(this);
add("North", status);
add("South", buttons);
add("Center", display);
for (int i = 0; i < accounts.length; i ++)
accounts[i] = 100000;
start();
validate();
setSize(700, 300);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{ System.exit(0); }
}
);
}
public synchronized void transfer(int from, int into, int amount)
{
if ((accounts[from] >= amount) && (from != into))
{
int newAmountFrom = accounts[from] - amount;
int newAmountTo = accounts[into] + amount;
wasteSomeTime();
accounts[from] = newAmountFrom;
accounts[into] = newAmountTo;
}
status.setText("transfers completed: " + counter ++);
}
private void start()
{
stop();
for (int i = 0; i < accounts.length; i ++)
customer[i] = new Customer(i, this);
}
private void stop()
{
for (int i = 0; i < accounts.length; i ++)
{
if (customer[i] != null)
customer[i].halt();
}
}
private void wasteSomeTime()
{
try
{ Thread.sleep(WASTE_TIME); }
catch (InterruptedException ie)
{ System.err.println("Error: " + ie); }
}
private void showAccounts()
{
int sum = 0;
for (int i = 0; i < accounts.length; i ++)
{
sum += accounts[i];
display.append("\naccount " + i + ": $" + accounts[i]);
}
display.append("\ntotal amount: $" + sum);
display.append("\ntotal transfers: " + counter + "\n");
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == show)
showAccounts();
else if (ae.getSource() == start)
start();
else if (ae.getSource() == stop)
stop();
}
public static void main(String args[])
{
Bank bank = new Bank();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -