Java實現發紅包模擬


1、先畫界面

package com.cmk;


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
 *
 */
public abstract class RedPacketFrame extends JFrame {

    private static final long serialVersionUID = 1L;
    
    private static final String DIR = "E:\\mycode\\Hongbao\\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;
    }


}
RedPacketFrame

2、建立紅包打開方式的接口

package com.cmk; 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); }
OpenMode

3、建立界面的實現類

 

package com.cmk;

public class MyRed extends RedPacketFrame{

    public MyRed(String title) {
        super(title);
        
    }

}
MyRed

 

4、設計紅包的打開方式

 (1)平均分

 

package com.cmk;

import java.util.ArrayList;

public class NormalMode implements OpenMode {

    @Override
    public ArrayList<Integer> divide(int totalMoney, int totalCount) {
        
        ArrayList<Integer> list=new ArrayList<>();
        int flag=totalMoney%totalCount;
        int money=totalMoney/totalCount;
        if(flag==0)
        {
            for(int i=0;i<totalCount;i++)
            {
                list.add(money);
            }
        }
        else
        {
            for(int i=0;i<totalCount-1;i++)
            {
                list.add(money);
                totalMoney-=money;
            }
            list.add(totalMoney);
        }
        return list;
    }
    

}
NormalMode

 

  (2)隨機分

package com.cmk;

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

public class RandomMode implements OpenMode {

    @Override
    public ArrayList<Integer> divide(int totalMoney, int totalCount) {
        
        ArrayList<Integer> list =new ArrayList<>();
        int leftMoney=totalMoney;//剩余錢數
        int leftCount=totalCount;//剩余人數
        Random r=new Random();
        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;
    }
}
RandomMode

 

5、運行結果:

main方法:

package com.cmk;

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        MyRed my=new MyRed("QQ紅包");
        my.setOwnerName("馬雲");//設置發紅包人的名稱
        //普通紅包
        OpenMode normal =new NormalMode();
        my.setOpenWay(normal);
        //my.setOpenWay(new RandomMode());
    }

}
Main

 

 

 

 

 

 可以改進的地方:

   錢數的設置,可以對錢數的上下限和小數點位數進行改進。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM