//放入文件 F1.java中
//result1.src.result1.F1.java
package result1;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
//模拟银行存取钱
class JieMian extends JFrame {
String string[] = new String[3];
JButton jButton[] = new JButton[3];
JLabel jLabel[] = new JLabel[3];
public JieMian() {
// TODO Auto-generated constructor stub
setSize(400, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("建设银行");
setLayout(new GridLayout(3, 2));
for (int i = 0; i < jButton.length; i++) {
// 3个按钮
jButton[i] = new JButton("确定");
}
string[0] = new String("存钱");
string[1] = new String("取钱");
string[2] = new String("余额");
for (int i = 0; i < 3; i++) {
jLabel[i] = new JLabel(string[i]);
}
for (int i = 0; i < jButton.length; i++) {
add(jLabel[i]);
jLabel[i].setFont(new Font("黑体",Font.ITALIC,50));
jButton[i].setBackground(Color.red);
add(jButton[i]);
}
jButton[0].addActionListener(new Tf3());
jButton[1].addActionListener(new Tf());
jButton[2].addActionListener(new Tf1());
validate();
}
}
class Tf3 implements ActionListener{
public void actionPerformed(ActionEvent event) {
// 存钱
Bank bank = new Bank();
Scanner scanner = new Scanner(System.in);
System.out.print("请输入存钱数:");
double monkey = scanner.nextDouble();
bank.setMoney(monkey);
}
}
class Tf implements ActionListener {
public void actionPerformed(ActionEvent event) {
// 取钱
Bank bank = new Bank();
System.out.print("请输入取钱金额:");
Scanner scanner = new Scanner(System.in);
bank.take(scanner.nextDouble());
//重点,scanner不能关闭,因为要实现多次输入
}
}
class Tf1 implements ActionListener {
public void actionPerformed(ActionEvent event) {
// 账户余额
Bank bank = new Bank();
JOptionPane.showMessageDialog(null, "余额为:" + bank.getMoney());
}
}
class Bank {
// 银行类
static double money = 200;// 类变量,类名和对象名直接引用
public void take(double monkey) {
// 类方法,取钱方法
// 定义同步线程保护数据方法,同一时刻调用方法的线程只能排队
money = money - monkey;
}
public void setMoney(double monkey) {
// 存钱方法
money = money + monkey;
}
public double getMoney() {
// 查看帐户余额
return money;
}
}
//测试程序放入F2.java中
//路径 result.src.result1.F2.java
public class F2 {
public static void main(String[] args) {
new JieMian();
}
}