【從零開始學 Java 程式設計】樂透選號程式

【從零開始學 Java 程式設計】 線上教學課程目錄,使用 Java 程式語言,開發應用程式。

樂透選號程式

學習 BoxLayout、GridBagLayout 佈局與處理多個 JCheckBox 複選框狀態。

執行畫面

完整程式碼

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;


public class DemoLotterySelection {
    private int currentCount = 0;
    private final int maxCount = 6;
    private ArrayList<JCheckBox> jCheckBoxArrayList = new ArrayList<>();

    public void addComponentsToPane(Container pane) {

        Box boxNorth = Box.createVerticalBox();

        JLabel jLabelTitle = new JLabel("大樂透");
        jLabelTitle.setFont(new Font("Courier New", Font.BOLD, 30));
        boxNorth.add(jLabelTitle);

        JLabel jLabelDescription = new JLabel("請從 1 ~ 49 個號碼中,任選6個號碼進行投注");
        jLabelDescription.setBorder(new EmptyBorder(20, 0, 0, 0));
        boxNorth.add(jLabelDescription);

        boxNorth.setBorder(new EmptyBorder(20, 20, 10, 10));
        pane.add(boxNorth, BorderLayout.NORTH);

        JPanel jPanelNumSel = new JPanel();
        GridBagLayout gridBagLayout = new GridBagLayout();
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.fill = GridBagConstraints.BOTH;//左右對齊
        jPanelNumSel.setLayout(gridBagLayout);
        createCheckBox(jPanelNumSel, gridBagLayout, gridBagConstraints, 1, 49);
        jPanelNumSel.setBorder(new EmptyBorder(10, 10, 10, 10));
        pane.add(jPanelNumSel, BorderLayout.CENTER);

        Box boxSouth = Box.createHorizontalBox();

        JButton btnBetting = new JButton("投注");
        btnBetting.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showSelNum(pane);
            }
        });
        boxSouth.add(Box.createHorizontalGlue());
        boxSouth.add(btnBetting);

        JButton btnRandom = new JButton("電腦隨機");
        btnRandom.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clearAllSelect();

                for (int i = 0; i < 6; i++) {
                    //todo 這樣亂數會有 Bug,應該過濾掉重覆的值
                    int randomNum = (int) (Math.random() * 42 + 1);
                    jCheckBoxArrayList.get(randomNum).setSelected(true);
                    currentCount++;
                }
            }
        });
        boxSouth.add(btnRandom);

        JButton btnClearAll = new JButton("重選");
        btnClearAll.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clearAllSelect();
            }
        });
        boxSouth.add(btnClearAll);

        pane.add(boxSouth, BorderLayout.SOUTH);

    }

    private void showSelNum(Container pane) {
        String tempSel = "";
        int count = 0;

        for (int i = 0; i < jCheckBoxArrayList.size(); i++) {
            if (jCheckBoxArrayList.get(i).isSelected()) {
                tempSel += jCheckBoxArrayList.get(i).getText() + " ";
                count++;
            }
        }

        if (count == 0 || count < 6) {
            JOptionPane.showMessageDialog(pane, "要選六個號碼,才能投注喔!", "錯誤", JOptionPane.ERROR_MESSAGE);
        } else {
            clearAllSelect();
            JOptionPane.showMessageDialog(pane, "投注號碼: " + tempSel, "祝您中獎~", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void clearAllSelect() {
        currentCount = 0;
        for (JCheckBox cb : jCheckBoxArrayList) {
            cb.setSelected(false);
        }
    }

    private void createCheckBox(Container pane, GridBagLayout gridBagLayout, GridBagConstraints gridBagConstraints, int startVal, int EndVal) {
        for (int i = startVal; i <= EndVal; i++) {
            JCheckBox cb = new JCheckBox(Integer.toString(i));
            jCheckBoxArrayList.add(cb);
            cb.setFont(new Font("Courier New", Font.BOLD, 20));
            gridBagLayout.setConstraints(cb, gridBagConstraints);

            if (i == 9 || i == 19 || i == 29 || i == 39) {
                //換行
                gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
            } else {
                //重設寬度
                gridBagConstraints.gridwidth = 1;
            }

            cb.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JCheckBox cb = (JCheckBox) e.getSource();
                    if (cb.isSelected()) {
                        if (currentCount >= maxCount) {
                            cb.setSelected(false);
                            JOptionPane.showMessageDialog(pane, "最多只能選六個號碼!", "錯誤", JOptionPane.ERROR_MESSAGE);
                        } else {
                            currentCount++;
                        }
                    } else {
                        currentCount--;
                    }
                }
            });
            pane.add(cb);
        }
    }

    public DemoLotterySelection() {
        JFrame frame = new JFrame("HKT線上教室");
        // 獲取螢幕解析度
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setSize(dimension.width / 2, dimension.height / 2);

        //設定視窗顯示在螢幕畫面中間位置
        int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
        frame.setLocation(x, y);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設定關閉可以關掉程式
        //在 Pane 畫面中加入元件
        addComponentsToPane(frame.getContentPane());
        frame.pack();
        frame.setVisible(true);
    }

    //最一開始程式進入點
    public static void main(String[] args) {
        //使用 invokeLater 確保 UI 在排程執行緒內
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new DemoLotterySelection();
            }
        });
    }
}

那這次的課程就介紹到這邊囉~
順帶一提,KT 線上教室,臉書粉絲團,會不定期發佈相關資訊,不想錯過最新資訊,不要忘記來按讚,加追蹤喔!也歡迎大家將這套課程分享給更多人喔。
我們下次再見囉!!!掰掰~

這個網誌中的熱門文章

2023 最新入門零基礎 Kotlin教學【從零開始學 Kotlin 程式設計】Kotlin 教學課程目錄 (Android Kotlin, IntelliJ IDEA, Android Studio, Android APP 開發教學)

nano 文字編輯器

16天記下7000單字

2022 最新入門零基礎 Flutter教學 【Flutter 程式設計入門實戰 30 天】Flutter 教學課程目錄 (IntelliJ IDEA 開發教學)