//放入檔案 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();
}
}