3.14饮料自动售货机
实现步骤
-
创建
VendingMachine类 -
实现饮料选择逻辑
实现代码(Java Swing)
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class VendingMachineGUI extends JFrame {
private JButton orangeJuiceButton;
private JButton beerButton;
private JButton coin5Button;
private JButton coin10Button;
private JTextArea displayArea;
private int currentCoin = 0;
public VendingMachineGUI() {
setTitle("饮料自动售货机");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
// 投币面板
JPanel coinPanel = new JPanel(new GridLayout(1, 2, 5, 5));
coin5Button = new JButton("投入5角");
coin10Button = new JButton("投入1元");
coinPanel.add(coin5Button);
coinPanel.add(coin10Button);
// 饮料选择面板
JPanel drinkPanel = new JPanel(new GridLayout(1, 2, 5, 5));
orangeJuiceButton = new JButton("橙汁");
beerButton = new JButton("啤酒");
drinkPanel.add(orangeJuiceButton);
drinkPanel.add(beerButton);
// 显示区域
displayArea = new JTextArea();
displayArea.setEditable(false);
displayArea.setFont(new Font("微软雅黑", Font.PLAIN, 16));
JScrollPane scrollPane = new JScrollPane(displayArea);
// 状态标签
JLabel stateLabel = new JLabel("当前投币: 0角", JLabel.CENTER);
stateLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
// 添加组件
add
