程式界面 — 庫存查詢
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class Exam5 {
public void createAndShow(){
JFrame frame = new JFrame("庫存查詢視窗"); // 建立頂層容器(視窗)
frame.setSize(400,300); // 設定容器大小
frame.setLocation(300,200); // 設定容器初始位置
frame.setVisible(true); // 設定容器可見
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 設定容器關閉方式
JPanel jPanel = new JPanel(); // 添加中間容器
JComboBox<String> jComboBox = new JComboBox<>(); // 添加下拉清單元件
jComboBox.addItem("請選擇商品"); // 添加下拉清單元素
jComboBox.addItem("色拉油");
jComboBox.addItem("齊心汽水");
jComboBox.addItem("米酒");
jComboBox.addItem("冰淇淋");
jComboBox.addItem("蛋糕");
JTextField jTextField1 = new JTextField(5); // 添加文本元件
JLabel jLabel1 = new JLabel("單價"); // 添加标簽元件
JTextField jTextField2 = new JTextField(5);
JLabel jLabel2 = new JLabel("庫存");
jComboBox.addActionListener(e->{ // 配置下拉清單動作監聽
String goods = (String) jComboBox.getSelectedItem(); // 傳回目前所選項并轉化為字元串的形式
if ("色拉油".equals(goods)){
jTextField1.setText("56");
jTextField2.setText("232");
}else if ("齊心汽水".equals(goods)){
jTextField1.setText("8");
jTextField2.setText("50");
}else if ("米酒".equals(goods)){
jTextField1.setText("10");
jTextField2.setText("109");
}else if ("冰淇淋".equals(goods)){
jTextField1.setText("20");
jTextField2.setText("48");
}else {
jTextField1.setText("90");
jTextField2.setText("30");
}
});
jPanel.add(jComboBox); // 元件的層層嵌套
jPanel.add(jLabel1);
jPanel.add(jTextField1);
jPanel.add(jLabel2);
jPanel.add(jTextField2);
frame.add(jPanel, BorderLayout.PAGE_START);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() { // 啟動一個線程去運作
@Override
public void run() {
Exam5 e = new Exam5();
e.createAndShow();
}
});
}
}