JAVA SE
簡易早午晚餐隨機選擇器
裡面的選項是寫死的
swing的撰寫有參考網路先進的文章
之前練習用的就給大家參考看看
package exercise;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class swing {
private JFrame mainFrame;
private JLabel headerLabel; //內文標題
private JLabel statusLabel; //按下按鈕之後的字
private JPanel controlPanel; //設置面板
public swing(){
prepareGUI(); //宣告畫面方法
}
public static void main(String[] args){ //MAIN
swing swingControlDemo = new swing();
swingControlDemo.showButtonDemo();
}
private void prepareGUI(){ //設置視窗畫面
mainFrame = new JFrame("今日特選餐點"); //視窗標題
mainFrame.setSize(400,450); //大小
mainFrame.setLayout(new GridLayout(4, 1)); //設置版面管理 設置行與列
mainFrame.addWindowListener(new WindowAdapter() { //設置監聽器以便事件
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("",JLabel.CENTER); //初始化內文標題置中
statusLabel = new JLabel("",JLabel.CENTER); //初始化按鈕後文字置中
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true); //設置可見
}
private void showButtonDemo(){
headerLabel.setText("請選擇餐別");
JButton brButton = new JButton("早餐");
JButton luButton = new JButton("午餐");
JButton diButton = new JButton("晚餐");
diButton.setHorizontalTextPosition(SwingConstants.LEFT);
brButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int rand = (int) (Math.random()*10); //隨機數字0-9
String breatfest[] = {"蛋餅","燒餅油條","鍋燒意麵" ,"三明治","飯糰","清粥小菜",
"鐵板麵","鬆餅","豬肉滿福堡加蛋","沒睡醒不吃"};
statusLabel.setText("為您精選今日早餐:"+breatfest[rand]); //選擇對應的食物
}
});
luButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int rand = (int) (Math.random()*10);
String lunch[] = {"咖哩拌飯","排骨便當","豬排便當" ,"拉麵",
"健康餐盒","沙拉","同事的便當","超商便當","炸醬麵","睡覺不吃"};
statusLabel.setText("為您精選今日午餐:"+lunch[rand]);
}
});
diButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int rand = (int) (Math.random()*10);
String dinner[] = {"水餃","泡麵","義大利麵" ,"鐵板燒","牛排","牛肉麵",
"燒肉","火鍋","迴轉壽司","睡覺不吃"};
statusLabel.setText("為您精選今日晚餐:"+dinner[rand]);
}
});
controlPanel.add(brButton); //面板中設置按鈕
controlPanel.add(luButton);
controlPanel.add(diButton);
mainFrame.setVisible(true); //設置可見
}
}
呈現出來的會是這個樣子
留言列表