import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Bank extends JFrame {
// 主面板pnBasic是用来装pnDate和标签文字的。
private JPanel pnBasic;
// 添加到主面板中的中间 pnDate面板是为了装表单的。
private JPanel pnDate;
// 添加到主面板中的北边 pnLabel面板是为了装欢迎词的
private JPanel pnLabel;
private int money = 0;
public Bank() {
pnBasic = new JPanel();
// 主面板pnBasic是用来装pnDate和标签文字的。
pnDate = new JPanel(new GridLayout(2, 2));
// pnDate面板是为了装表单的。
pnLabel = new JPanel();
JLabel top = new JLabel("欢迎来到中国银行!");
pnLabel.add(top);
// 先将数值添加在一个容器中并设置其在容器的右边,在将容器添加在网格的第一格
JPanel jp1 = new JPanel();
JLabel number = new JLabel("数值:");
final JTextField box = new JTextField(5);
jp1.add(number);
jp1.add(box);
JPanel jp2 = new JPanel();
JButton create = new JButton("新建银行账户");
jp2.add(create);
JButton take = new JButton("取款");
JButton in = new JButton("存款");
pnDate.add(jp1);
pnDate.add(jp2);
pnDate.add(take);
pnDate.add(in);
// 加一句下面的就好了
JPanel jpS = new JPanel();
final JLabel total = new JLabel("您现在的账户余额是:0 元");
jpS.add(total);
pnBasic.setLayout(new BorderLayout());
pnBasic.add(pnLabel, new BorderLayout().NORTH);
pnBasic.add(pnDate, new BorderLayout().CENTER);
pnBasic.add(jpS, new BorderLayout().SOUTH);
setContentPane(pnBasic);
//
setBounds(50, 50, 200, 200);
pack();
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
pack();
in.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (box.getText() != null && box.getText() != "") {
try {
int count = Integer.parseInt(box.getText());
if (count > 0) {
save(count);
total.setText("您现在的账户余额是:" + money + "元");
box.setText("");
}
} catch (Exception e1) {
System.out.println("您输入的数值必须是数字");
}
}
}
});
take.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (box.getText() != null && box.getText() != "") {
try {
int count = Integer.parseInt(box.getText());
if (count >= 0 && count <= money) {
draw(count);
total.setText("您现在的账户余额是:" + money + "元");
box.setText("");
} else {
System.out.println("你的余额不足,取款失败");
}
} catch (Exception e1) {
System.out.println("您输入的数值必须是数字");
}
}
}
});
create.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
total.setText("您现在的账户余额是:0元");
money = 0;
box.setText("");
}
});
}
// 存款的方法
public void save(int count) {
money += count;
}
// 取款的方法
public void draw(int count) {
money -= count;
}
public static void main(String[] args) {
new Bank();
}
}