java實現一個發紅包案例

先展示一下成果:
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
Main類:

package cn.itcast.day11.demo08;

import cn.itcast.day11.red.OpenMode;

/*
場景說明:
    紅包發出去之後,所有人都有紅包,大家搶完了之後,最後一個紅包給羣主自己。
大多數代碼都是現成的,我們需要做的就是填空題。
我們自己要做的事情有:
    1. 設置一下程序的標題,通過構造方法的字符串參數
    2. 設置羣主名稱
    3. 設置分發策略:平均,還是隨機?

紅包分發的策略:
    1. 普通紅包(平均):totalMoney / totalCount,餘數放在最後一個紅包當中。
    2. 手氣紅包(隨機):最少1分錢,最多不超過平均數的2倍。應該越發越少。
 */
public class Bootstrap {

    public static void main(String[] args) {
        MyRed red = new MyRed("發紅包案例");
        // 設置羣主名稱
        red.setOwnerName("王思聰");

        // 普通紅包
//        OpenMode normal = new NormalMode();
//        red.setOpenWay(normal);

        // 手氣紅包
        OpenMode random = new RandomMode();
        red.setOpenWay(random);
    }

}

調用生成紅包界面:

package cn.itcast.day11.demo08;

import cn.itcast.day11.red.RedPacketFrame;

public class MyRed extends RedPacketFrame {
    /**
     * 構造方法:生成紅包界面。
     *
     * @param title 界面的標題
     */
    public MyRed(String title) {
        super(title);
    }
}

生成隨機紅包的方法:

package cn.itcast.day11.demo08;

import cn.itcast.day11.red.OpenMode;

import java.util.ArrayList;
import java.util.Random;

public class RandomMode implements OpenMode {
    @Override
    public ArrayList<Integer> divide(final int totalMoney, final int totalCount) {
        ArrayList<Integer> list = new ArrayList<>();

        // 隨機分配,有可能多,有可能少。
        // 最少1分錢,最多不超過“剩下金額平均數的2倍”
        // 第一次發紅包,隨機範圍是0.01元~6.66元
        // 第一次發完之後,剩下的至少是3.34元。
        // 此時還需要再發2個紅包
        // 此時的再發範圍應該是0.01元~3.34元(取不到右邊,剩下0.01)

        // 總結一下,範圍的【公式】是:1 + random.nextInt(leftMoney / leftCount * 2);
        Random r = new Random(); // 首先創建一個隨機數生成器
        // totalMoney是總金額,totalCount是總份數,不變
        // 額外定義兩個變量,分別代表剩下多少錢,剩下多少份
        int leftMoney = totalMoney;
        int leftCount = totalCount;

        // 隨機發前n-1個,最後一個不需要隨機
        for (int i = 0; i < totalCount - 1; i++) {
            // 按照公式生成隨機金額
            int money = r.nextInt(leftMoney / leftCount * 2) + 1;
            list.add(money); // 將一個隨機紅包放入集合
            leftMoney -= money; // 剩下的金額越發越少
            leftCount--; // 剩下還應該再發的紅包個數,遞減
        }

        // 最後一個紅包不需要隨機,直接放進去就得了
        list.add(leftMoney);

        return list;
    }
}

生成隨機紅包方法的父類:

package cn.itcast.day11.red;

import java.util.ArrayList;

public interface OpenMode {
    /**
     * 請將totalMoney分成count份,保存到ArrayList<Integer>中,返回即可。
     *
     * @param totalMoney            總金額爲方便計算,已經轉換爲整數,單位爲分。
     * @param totalCount            紅包個數
     * @return ArrayList<Integer>	元素爲各個紅包的金額值,所有元素的值累和等於總金額。
     */
    ArrayList<Integer> divide(int totalMoney, int totalCount);
}

生成紅包的框架:

package cn.itcast.day11.red;


import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 紅包的框架 RedPacketFrame
 *
 * AWT / Swing / JavaFX
 *
 * @author 不是我
 */
public abstract class RedPacketFrame extends JFrame {

    private static final long serialVersionUID = 1L;
    
    private static final String DIR = "day11-code\\pic";

    private ArrayList<Integer> moneyList = null;

    private static int initMoney = 0;
    private static int totalMoney = 0; // 單位爲“分”
    private static int count = 0;

    private static HashMap<JPanel, JLabel> panelLable = new HashMap<>();

    // 設置字體
    private static Font fontYaHei = new Font("微軟雅黑", Font.BOLD, 20);
    private static Font msgFont = new Font("微軟雅黑", Font.BOLD, 20);
    private static Font totalShowFont = new Font("微軟雅黑", Font.BOLD, 40);
    private static Font nameFont = new Font("微軟雅黑", Font.BOLD, 40);
    private static Font showNameFont = new Font("微軟雅黑", Font.BOLD, 20);
    private static Font showMoneyFont = new Font("微軟雅黑", Font.BOLD, 50);
    private static Font showResultFont = new Font("微軟雅黑", Font.BOLD, 15);

    /**
     * 窗體大小 WIDTH:400 HEIGHT:600
     */
    private static final int FRAME_WIDTH = 416; // 靜態全局窗口大小
    private static final int FRAME_HEIGHT = 650;
    private static JLayeredPane layeredPane = null;

    /// private static JPanel contentPane = null;

    /**
     * page1:輸入頁面 - InputPanel . 組件和初始化!
     */
    private static JPanel inputPanel = new JPanel();

    // private static JTextField input_total = new JTextField("200"); // 測試用
    // private static JTextField input_count = new JTextField("3"); // 測試用
    private static JTextField input_total = new JTextField();
    private static JTextField input_count = new JTextField();
    private static JTextField input_people = new JTextField("30");
    private static JTextField input_msg = new JTextField("恭喜發財  ,  大吉大利");
    private static JTextField input_total_show = new JTextField("$ " + input_total.getText().trim());
    private static JLabel input_inMoney = new JLabel(); // 不可見
    private static JLabel input_bg_label = new JLabel(new ImageIcon(DIR + "\\01_input.jpg"));

    static {

        // 設置位置
        input_total.setBounds(200, 90, 150, 50);
        input_count.setBounds(200, 215, 150, 50);
        input_people.setBounds(90, 275, 25, 30);
        input_msg.setBounds(180, 340, 200, 50);
        input_total_show.setBounds(130, 430, 200, 80);
        input_inMoney.setBounds(10, 535, 380, 65);
        input_bg_label.setBounds(0, 0, 400, 600); // 背景

        // 設置字體
        input_total.setFont(fontYaHei);
        input_count.setFont(fontYaHei);
        input_people.setFont(fontYaHei);
        input_msg.setFont(msgFont);
        input_msg.setForeground(new Color(255, 233, 38)); // 字體顏色 爲金色
        input_total_show.setFont(totalShowFont);
        input_inMoney.setFont(fontYaHei);

        // 透明
        input_people.setOpaque(false);
        input_total_show.setOpaque(false);
        // 編 輯 -- 不可編輯
        input_people.setEditable(false);
        input_total_show.setEditable(false);

        // 邊界 -- 無
        input_total.setBorder(null);
        input_count.setBorder(null);
        input_people.setBorder(null);
        input_msg.setBorder(null);
        input_total_show.setBorder(null);

    }

    /**
     * page2:打開頁面 - openPanel . 組件和初始化!
     */
    private static JPanel openPanel = new JPanel();

    private static JTextField open_ownerName = new JTextField("誰誰誰");
    private static JLabel open_label = new JLabel(new ImageIcon(DIR + "\\02_open_2.gif"));
    private static JLabel open_bg_label = new JLabel(new ImageIcon(DIR + "\\02_open_1.jpg"));

    static {

        // 設置 位置.
        open_ownerName.setBounds(0, 110, 400, 50);
        open_bg_label.setBounds(0, 0, 400, 620);
        open_label.setBounds(102, 280, 200, 200);
        open_ownerName.setHorizontalAlignment(JTextField.CENTER);

        // 設置字體
        open_ownerName.setFont(nameFont);
        open_ownerName.setForeground(new Color(255, 200, 163)); // 字體顏色 爲金色

        // 背景色
        // open_name.setOpaque(false);
        open_ownerName.setBackground(new Color(219, 90, 68));

        // 不可編輯
        open_ownerName.setEditable(false);
        // 邊框
        open_ownerName.setBorder(null);

    }

    /**
     * page3:展示頁面 - showPanel . 組件和初始化!
     */
    private static JPanel showPanel = new JPanel();
    private static JPanel showPanel2 = new JPanel();
    private static JScrollPane show_jsp = new JScrollPane(showPanel2);

    private static JLabel show_bg_label = new JLabel(new ImageIcon(DIR + "\\03_money_1.jpg"));

    private static JTextField show_name = new JTextField("用戶名稱");
    private static JTextField show_msg = new JTextField("祝福信息");
    private static JTextField show_money = new JTextField("99.99");
    private static JTextField show_result = new JTextField(count + "個紅包共" + (totalMoney / 100.0) + "元,被搶光了");

    static {
        // 分別設置水平和垂直滾動條自動出現
        // jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        // jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        /*
         * 兩部分 頁面 . 1.本人獲得的紅包-- showPanel 2.別人獲得的紅包-- show_jsp
         */
        show_name.setBounds(125, 180, 100, 30);
        show_name.setOpaque(false);
        show_name.setBorder(null);
        show_name.setFont(showNameFont);

        show_msg.setBounds(0, 220, 400, 30);
        show_msg.setOpaque(false);
        show_msg.setBorder(null);
        show_msg.setFont(msgFont);
        show_msg.setHorizontalAlignment(JTextField.CENTER);

        show_money.setBounds(0, 270, 250, 40);
        show_money.setOpaque(false);
        show_money.setBorder(null);
        show_money.setFont(showMoneyFont);
        show_money.setForeground(new Color(255, 233, 38)); // 字體顏色 爲金色
        show_money.setHorizontalAlignment(SwingConstants.RIGHT);

        show_result.setBounds(10, 460, 400, 20);
        show_result.setOpaque(false);
        show_result.setBorder(null);
        show_result.setFont(showResultFont);
        show_result.setForeground(new Color(170, 170, 170)); // 字體顏色 爲灰色

        // 設置 圖片.
        show_bg_label.setBounds(0, 0, 400, 500);

    }

    static {

        // 頁面和 背景的對應關係.
        panelLable.put(inputPanel, input_bg_label);
        panelLable.put(openPanel, open_bg_label);
        panelLable.put(showPanel, show_bg_label);
    }

    private void init() {
        // 層次面板-- 用於設置背景
        layeredPane = this.getLayeredPane();
//        System.out.println("層次面板||" + layeredPane);
        // System.out.println(layeredPane);

        // 初始化框架 -- logo 和基本設置
        initFrame();
        // 初始化 三個頁面 -- 準備頁面
        initPanel();

        // 2.添加 頁面 --第一個頁面, 輸入 panel 設置到 頁面上.
        setPanel(inputPanel);

        // 3.添加 監聽
        addListener();
    }


    /**
     * 初始化框架 -- logo 和基本設置
     */
    private void initFrame() {
        // logo
        this.setIconImage(Toolkit.getDefaultToolkit().getImage(DIR + "\\logo.gif"));
//        System.out.println("LOGO初始化...");

        // 窗口設置
        this.setSize(FRAME_WIDTH, FRAME_HEIGHT); // 設置界面大小
        this.setLocation(280, 30); // 設置界面出現的位置
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLayout(null);

        // 測試期 註釋 拖 拽 , 運行放開
        // this.setResizable(false);
        this.setVisible(true);
    }

    /**
     * 初始化頁面-- 準備三個頁面
     */

    private void initPanel() {
//        System.out.println("頁面初始化...");
        initInputPanel();
        initOpenPanel();
        initShowPanel();

    }

    private void initInputPanel() {

        inputPanel.setLayout(null);
        inputPanel.setBounds(0, -5, 400, 600);

        // this.add(bg_label);
        inputPanel.add(input_total);
        inputPanel.add(input_count);
        inputPanel.add(input_people);
        inputPanel.add(input_msg);
        inputPanel.add(input_total_show);
        inputPanel.add(input_inMoney);

//        System.out.println("輸入頁面||" + inputPanel);

    }

    private void initOpenPanel() {
        openPanel.setLayout(null);
        openPanel.setBounds(0, 0, 400, 600);
        // this.add(bg_label);
        openPanel.add(open_ownerName);
        openPanel.add(open_label);
//        System.out.println("打開頁面||" + openPanel);
    }

    private void initShowPanel() {
        showPanel.setLayout(null);
        showPanel.setBounds(10, 10, 300, 600);

        // ==============
        showPanel.add(show_name);
        showPanel.add(show_msg);
        showPanel.add(show_money);
        showPanel.add(show_result);
//        System.out.println("展示頁面||" + showPanel);
        // ====================================
        // showPanel2.setLayout(null);
        // showPanel2.setBounds(0, 500, 401, 300);

        showPanel2.setPreferredSize(new Dimension(300, 1000));
        showPanel2.setBackground(Color.white);

        show_jsp.setBounds(0, 500, 400, 110);

    }

    /**
     * 每次打開頁面, 設置 panel的方法
     */
    private void setPanel(JPanel panel) {
        // 移除當前頁面
        layeredPane.removeAll();

//        System.out.println("重新設置:新頁面");
        // 背景lable添加到layeredPane的默認層
        layeredPane.add(panelLable.get(panel), JLayeredPane.DEFAULT_LAYER);

        // 面板panel設置爲透明
        panel.setOpaque(false);

        // 面板panel 添加到 layeredPane的modal層
        layeredPane.add(panel, JLayeredPane.MODAL_LAYER);
    }

    // private void setShowPanel(JPanel show) {
    // setPanel(show);
    // layeredPane.add(show_jsp, JLayeredPane.MODAL_LAYER);
    //
    // }

    /**
     * 設置組件的監聽器
     */
    private void addListener() {

        input_total.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                // System.out.println(e);
                String input_total_money = input_total.getText();
                input_total_show.setText("$ " + input_total_money);
            }
        });

        input_count.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                // System.out.println(e);
//                System.out.println("個數:" + input_count.getText());
            }
        });
        input_msg.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                // System.out.println(e);
//                System.out.println("留言:" + input_msg.getText());
            }
        });

        input_inMoney.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {

                    // 獲取頁面的值.
                    totalMoney = (int) (Double.parseDouble(input_total.getText()) * 100); // 轉換成"分"
                    count = Integer.parseInt(input_count.getText());
                    if (count > 30) {
                        JOptionPane.showMessageDialog(null, "紅包個數不得超過30個", "紅包個數有誤", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }

                    initMoney = totalMoney;

                    System.out.println("總金額:[" + totalMoney + "]分");
                    System.out.println("紅包個數:[" + count + "]個");

                    input_inMoney.removeMouseListener(this);

//                    System.out.println("跳轉-->打開新頁面");

                    // 設置羣主名稱
                    open_ownerName.setText(ownerName);
                    // 設置打開頁面
                    setPanel(openPanel);

                } catch (Exception e2) {
                    JOptionPane.showMessageDialog(null, "請輸入正確【總金額】或【紅包個數】", "輸入信息有誤", JOptionPane.ERROR_MESSAGE);

                }
            }
        });

        // open_ownerName ,點擊 [名稱],觸發的方法 , 提示如何設置羣主名稱.

        open_ownerName.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                JOptionPane.showMessageDialog(null, "請通過【setOwnerName】方法設置羣主名稱", "羣主名稱未設置",
                        JOptionPane.QUESTION_MESSAGE);
            }
        });

        // open label , 點擊 [開],觸發的方法,提示如何設置打開方式.
        open_label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (openWay == null) {
                    JOptionPane.showMessageDialog(null, "請通過【setOpenWay】方法設置打開方式", "打開方式未設置",
                            JOptionPane.QUESTION_MESSAGE);
                    return;
                }

//                System.out.println("跳轉-->展示頁面");

                moneyList = openWay.divide(totalMoney, count);

//                System.out.println(moneyList);
                /*
                 * showPanel 添加數據
                 *
                 */
                show_name.setText(ownerName);
                show_msg.setText(input_msg.getText());
                if (moneyList.size() > 0) {
                    show_money.setText(moneyList.get(moneyList.size() - 1) / 100.0 + "");
                }
                show_result.setText(count + "個紅包共" + (initMoney / 100.0) + "元,被搶光了");

                open_label.removeMouseListener(this);

                setPanel(showPanel);

                // 添加數據
                for (int i = 0; i < moneyList.size(); i++) {

                    JTextField tf = new JTextField();
                    tf.setBorder(null);
                    tf.setFont(showNameFont);
                    tf.setHorizontalAlignment(JTextField.LEFT);
                    if (i == moneyList.size() - 1) {
                        tf.setText(ownerName + ":\t" + moneyList.get(i) / 100.0 + "元");

                    } else {

                        tf.setText("羣成員-" + i + ":\t" + moneyList.get(i) / 100.0 + "元");
                    }
                    showPanel2.add(tf);
                }

                layeredPane.add(show_jsp, JLayeredPane.MODAL_LAYER);
            }

        });

    }

    /* ======================================================================
     * **********************************************************************
     * * 以上代碼均爲頁面部分處理,包括佈局/互動/跳轉/顯示等,大家							*
     * *																	*
     * *																	*
     * **********************************************************************
     * ======================================================================
     */

    /**
     * ownerName : 羣主名稱
     */
    private String ownerName = "誰誰誰"; // 羣主名稱
    /**
     * openWay : 紅包的類型 [普通紅包/手氣紅包]
     */
    private OpenMode openWay = null;


    /**
     * 構造方法:生成紅包界面。
     *
     * @param title 界面的標題
     */

    public RedPacketFrame(String title) {
        super(title);

        // 頁面相關的初始化
        init();
    }

    public void setOwnerName(String ownerName) {
        this.ownerName = ownerName;
    }

    public void setOpenWay(OpenMode openWay) {
        this.openWay = openWay;
    }


}
發佈了281 篇原創文章 · 獲贊 131 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章