java實現聯機五子棋

lai123 8年前發布 | 3K 次閱讀 Java

a.jpg    

Config.xml ~ 122B         

<?xml version="1.0" encoding="UTF-8"?>
<CONFIG>
    <SIZE>50</SIZE>
    <ROW>8</ROW>
    <CLOUNM>8</CLOUNM>
</CONFIG>

Main.java ~ 112B         

import panel.MainUI;

public class Main {
    public static void main(String[] args) {
        new MainUI();
    }
}

[文件] Config.java ~ 5KB         

package panel;

import java.awt.Color;
import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Config {
    private static int port;
    /**
     * ?à×ó±??ò?àà?
     */
    public static final int STARTX = 50;
    /**
     * ?Yé?±??ò?àà?
     */
    public static final int STARTY = 90;
    /**
     * ????
     */
    public static int SIZE = 50;
    /**
     * DDêy
     */
    public static int ROW = 10;
    /**
     * áDêy
     */
    public static int CLOUNM = 10;
    private static Color color = Color.BLACK;
    private static byte[][] chess ;
    private static int[] notify = { -1, -1 };

    static {
        try {
            File f = new File("Config.xml");
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(f);
            NodeList nl = doc.getElementsByTagName("CONFIG");
            // SIZE=Integer.parseInt(doc.getElementsByTagName("SIZE").item(0).getFirstChild().getNodeValue()));

            for (int i = 0; i < nl.getLength(); i++) {
                SIZE = Integer.parseInt(doc.getElementsByTagName("SIZE")
                        .item(i).getFirstChild().getNodeValue());
                ROW = Integer.parseInt(doc.getElementsByTagName("ROW").item(i)
                        .getFirstChild().getNodeValue());
                CLOUNM = Integer.parseInt(doc.getElementsByTagName("CLOUNM")
                        .item(i).getFirstChild().getNodeValue());
                // System.out.println(SIZE+" "+ROW+ " "+CLOUNM);
            }
            chess = new byte[ROW + 1][CLOUNM + 1];
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void setX(int x) {
        notify[0] = x;
    }

    public static int getX() {
        return notify[0];
    }

    public static void setY(int y) {
        notify[1] = y;
    }

    public static int getY() {
        return notify[1];
    }

    public static void clearNotify() {
        notify[0] = notify[1] = -1;
    }

    /**
     * éè????×ó??é?
     */
    public static void setColor(Color cr) {
        color = cr;
    }
    public static void exchangeColor(){
        color=(color==Color.BLACK)?Color.WHITE:Color.BLACK;
    }
    /**
     * ??μ???×ó??é?
     */
    public static Color getColor() {
        return color;
    }

    /**
     * ?D??êó±ê?ùμ??÷????ê?·??é????×ó
     */
    public static boolean isChessMan(int x, int y, Color color) {
        int j = (x - STARTX) / SIZE;
        int i = (y - STARTY) / SIZE;
        if (chess[i][j] != 0)
            return false;
        else {
            chess[i][j] = (color == Color.BLACK) ? (byte) 1 : -1;
            return true;
        }
    }

    /**
     * ?D??êó±ê?ùμ??÷×?±êê?·??é????×ó
     */
    public static boolean isChessMan(byte j, byte i, Color color) {
        if (chess[i][j] != 0)
            return false;
        else {
            chess[i][j] = (color == Color.BLACK) ? (byte) 1 : -1;
            return true;
        }
    }

    /**
     * ???????ì
     */
    public static void resetChess(byte[][] buf) {
        chess = buf;
    }

    /**
     * ?D??ê?·?ê¤à?
     */
    public static boolean isWin(Color color) {
        boolean flag = false;
        int n = 0;
        int c = (color == Color.BLACK) ? 1 : -1;
        // ?D??áD
        for (int i = 0; i <= ROW; i++) {
            for (int j = 0; j <= CLOUNM; j++) {
                if (chess[i][j] == c && flag == false) {
                    n = 1;
                    flag = true;
                } else if (chess[i][j] == c && flag == true) {
                    n++;
                } else if (chess[i][j] != c) {
                    n = 0;
                    flag = false;
                }
                if (5 == n) {
                    n = 0;
                    flag = false;
                    return true;
                }
            }
        }
        n = 0;
        flag = false;
        // ?D??DD
        for (int j = 0; j <= CLOUNM; j++) {
            for (int i = 0; i <= ROW; i++) {
                if (chess[i][j] == c && flag == false) {
                    n = 1;
                    flag = true;
                } else if (chess[i][j] == c && flag == true) {
                    n++;
                } else if (chess[i][j] != c) {
                    n = 0;
                    flag = false;
                }
                if (5 == n) {
                    n = 0;
                    flag = false;
                    return true;
                }
            }
        }
        n = 0;
        flag = false;
        // ?D??×óD±
        for (int i = 0; i <= ROW; i++) {
            for (int j = 0; j <= CLOUNM; j++) {
                for (int ii = i, jj = j; ii <= ROW && jj >= 0; ii++, jj--) {
                    if (chess[ii][jj] == c && flag == false) {
                        n = 1;
                        flag = true;
                    } else if (chess[ii][jj] == c && flag == true) {
                        n++;
                    } else if (chess[ii][jj] != c) {
                        n = 0;
                        flag = false;
                    }
                    if (5 == n) {
                        n = 0;
                        flag = false;
                        return true;
                    }
                }
            }
        }
        n = 0;
        flag = false;
        // ?D??óòD±
        for (int i = 0; i <= ROW; i++) {
            for (int j = 0; j <= CLOUNM; j++) {
                for (int ii = i, jj = j; jj <= CLOUNM && ii <= ROW; ii++, jj++) {
                    if (chess[ii][jj] == c && flag == false) {
                        n = 1;
                        flag = true;
                    } else if (chess[ii][jj] == c && flag == true) {
                        n++;
                    } else if (chess[ii][jj] != c) {
                        n = 0;
                        flag = false;
                    }
                    if (5 == n) {
                        n = 0;
                        flag = false;
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * éè?????úo?
     */
    public static void setPort(int p) {
        port = p;
        // System.out.println(port);
    }

    /**
     * ??è????úo?
     */
    public static int getPort() {
        return port;
    }

    /**
     * ??????×ó
     */
    public static void clearChess() {
        chess = new byte[ROW + 1][CLOUNM + 1];
    }

    /**
     * ??μ???×ó
     */
    public static byte[][] getChess() {
        return chess;
    }
}

[文件] MainUI.java ~ 3KB         

package panel;

import game.ChessUtils;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class MainUI extends JFrame {
    private MenuListener menupolice;
    private JMenuBar menubar;
    private JMenu menu;
    private JMenuItem itemStart;
    private JMenuItem itemjoin;
    private JMenuItem itemOver;

    public MainUI() {
        setSize(2 * Config.STARTX + Config.CLOUNM * Config.SIZE, Config.STARTY
                + Config.SIZE * (Config.ROW + 1));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        itemStart = new JMenuItem("創建游戲");
        itemjoin = new JMenuItem("加入游戲");
        itemOver = new JMenuItem("結束游戲");
        menu = new JMenu("菜單");
        menubar = new JMenuBar();
        menu.add(itemStart);
        menu.add(itemjoin);
        menu.add(itemOver);
        menubar.add(menu);
        add(menubar, BorderLayout.NORTH);

        menupolice = new MenuListener(itemStart, itemjoin, itemOver, this);

        itemStart.addActionListener(menupolice);
        itemjoin.addActionListener(menupolice);
        itemOver.addActionListener(menupolice);

        // 添加窗體背景圖片
        ImageIcon icon = new ImageIcon("1.jpg");
        JLabel label = new JLabel(icon);
        getLayeredPane().add(label, new Integer(Integer.MIN_VALUE));
        label.setBounds(0, 0, 1000,1000);
        ((JPanel) this.getContentPane()).setOpaque(false);

        ChessUtils.locateFrameCenter(this);

        setVisible(true);
        setTitle("五子棋");
    }

    /**
     * 重寫父類重繪方法
     */
    public void paint(Graphics g) {
        // 調用父類重繪方法
        super.paint(g);
        drawLine(g);
        drawChessMan(g);
    }

    /**
     * 重繪棋盤
     */
    private void drawLine(Graphics g) {
        g.setColor(Color.BLACK);
        // 縱線
        for (int i = 0; i <= Config.CLOUNM; i++) {
            g.drawLine(Config.SIZE * i + Config.STARTX, Config.STARTY,
                    Config.SIZE * i + Config.STARTX, (Config.ROW) * Config.SIZE
                            + Config.STARTY);
        }
        // 橫線
        for (int i = 0; i <= Config.ROW; i++) {
            g.drawLine(Config.STARTX, Config.STARTY + Config.SIZE * i,
                    Config.SIZE * (Config.CLOUNM) + Config.STARTX,
                    Config.STARTY + Config.SIZE * i);
        }
    }

    /**
     * 重繪棋子
     */
    private void drawChessMan(Graphics g) {
        g.setColor(Config.getColor());
        byte[][] chess = Config.getChess();
        // System.out.println(Config.ROW);
        for (int i = 0; i <= Config.ROW; i++) {
            for (int j = 0; j <= Config.CLOUNM; j++) {
                if (1 == chess[i][j]) {
                    g.setColor(Color.BLACK);
                    g.fillOval((j * Config.SIZE + Config.STARTX)
                            - (Config.SIZE / 2),
                            (i * Config.SIZE + Config.STARTY)
                                    - (Config.SIZE / 2), Config.SIZE - 5,
                            Config.SIZE - 5);
                }
                if (-1 == chess[i][j]) {
                    g.setColor(Color.WHITE);
                    g.fillOval((j * Config.SIZE + Config.STARTX)
                            - (Config.SIZE / 2),
                            (i * Config.SIZE + Config.STARTY)
                                    - (Config.SIZE / 2), Config.SIZE - 5,
                            Config.SIZE - 5);
                }
            }
        }
        // g.setColor(Color.BLACK);
    }
}

[文件] MyListener.java ~ 3KB         

package panel;

import game.GameClient;
import game.GameServer;
import game.MyDialog;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JMenuItem;

/**
 * 處理輸贏判斷以及坐標轉換
 * 
 * @author chenj_000
 *
 */
public class MyListener implements MouseListener {

    /**
     * 鼠標點擊觸發
     */
    public void mousePressed(MouseEvent e) {
        // 1,獲得焦點坐標
        int x = e.getX();
        int y = e.getY();
        x = ((x - Config.STARTX) + (Config.SIZE / 2)) / Config.SIZE
                * Config.SIZE + Config.STARTX;
        y = ((y - Config.STARTY) + (Config.SIZE / 2)) / Config.SIZE
                * Config.SIZE + Config.STARTY;
        // 2,判斷坐標是否閑置
        if (!Config.isChessMan(x, y, Config.getColor()))
            return;
        // 3,若坐標可用,則向配置文件發送坐標信息
        Config.setX(x);
        Config.setY(y);
    }

    public void mouseClicked(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }
}

/**
 * 菜單項監視器
 * 
 * @author chenj_000
 *
 */
class MenuListener implements ActionListener {
    private JMenuItem itemStart;
    private JMenuItem itemjoin;
    private JMenuItem itemOver;
    private JFrame frame;
    private Thread start;
    private Thread join;
    private GameServer server;
    private GameClient client;

    public MenuListener(JMenuItem Start, JMenuItem join, JMenuItem Over,
            JFrame f) {
        itemStart = Start;
        itemjoin = join;
        itemOver = Over;
        frame = f;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JMenuItem item = (JMenuItem) e.getSource();
        if (item.equals(itemStart)) {
            server=new GameServer(frame);
            start = new Thread(server);
            start.start();
            itemStart.setEnabled(false);
            itemjoin.setEnabled(false);
        } else if (item.equals(itemjoin)) {
            client=new GameClient(frame);
            join = new Thread(client);
            join.start();
            itemStart.setEnabled(false);
            itemjoin.setEnabled(false);
        } else if (item.equals(itemOver)) {
            if (null != start)
                try {
                    server.threadDestory();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            if (null != join)
                try {
                    client.threadDestory();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            itemStart.setEnabled(true);
            itemjoin.setEnabled(true);
            Config.clearChess();
            new MyDialog(frame, "棋局已經重置", false).setVisible(true);
        }
    }
}

[文件] ChessUtils.java ~ 1KB         

package game;

import java.awt.*;
import javax.swing.*;

/**
 * 本類為其他類提供可靜態引用的方法
 * 
 * @author chenj_000
 *
 */
public class ChessUtils {
    /**
     * 將一個容器的位置設置為居中
     */
    public static void locateFrameCenter(JFrame frame) {
        int frameWidth = frame.getWidth();
        int frameHeight = frame.getHeight();
        /* Toolkit是所有 Abstract Window Toolkit 實際實現的抽象超類。 getDefaultToolkit()獲取默認工具包。*/
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        /* Dimension 類封裝單個對象中組件的寬度和高度(精確到整數)。 getScreenSize() 獲取當前顯示器尺寸 */
        Dimension screen = toolkit.getScreenSize();
        int screenWidth = screen.width;
        int screenHeight = screen.height;
        /* 調整當前容器位置居中 */
        frame.setLocation((screenWidth - frameWidth) / 2,
                (screenHeight - frameHeight) / 2);
    }

    /**
     * 設置對話框居中顯示
     */
    public static void locateDialogCenter(JDialog dialog) {
        int frameWidth = dialog.getWidth();
        int frameHeight = dialog.getHeight();
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screen = toolkit.getScreenSize();
        int screenWidth = screen.width;
        int screenHeight = screen.height;
        dialog.setLocation((screenWidth - frameWidth) / 2,
                (screenHeight - frameHeight) / 2);
    }
}

[文件] GameClient.java ~ 5KB     (13)    

package game;

import java.awt.Color;
import java.awt.Graphics;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import panel.Config;
import panel.MyListener;

public class GameClient implements Runnable {
    private Socket client;
    private int port;
    private String ip;
    private JFrame frame;
    private InputStream in;
    private OutputStream out;
    private String name;
    private boolean flag = false;

    public GameClient(JFrame frame) {
        this.frame = frame;
        init();
    }

    /**
     * 判斷是否建立了連接
     */
    private boolean confirm() throws IOException {
        byte[] buf = new byte[64];
        int n = in.read(buf);
        name = new String(buf, 0, n);
        return (name.length() > 0) ? true : false;
    }

    /**
     * 接收初始化信息
     * 
     * @throws IOException
     */
    private void resetUI() throws IOException {
        byte buf[] = new byte[64];
        int n = in.read(buf);
        // System.out.println(s);
        String[] numberStrs = new String(buf, 0, n).split("#");
        // System.out.println(numberStrs.toString());
        Config.SIZE = Integer.parseInt(numberStrs[0]);
        Config.ROW = Integer.parseInt(numberStrs[1]);
        Config.CLOUNM = Integer.parseInt(numberStrs[2]);
        frame.setSize(2 * Config.STARTX + Config.CLOUNM * Config.SIZE,
                Config.STARTY + Config.SIZE * (Config.ROW + 1));
        Config.resetChess(new byte[Config.ROW + 1][Config.CLOUNM + 1]);
        frame.paint(frame.getGraphics());
    }

    public void run() {
        try {
            InetAddress address = InetAddress.getByName(ip);
            client = new Socket(address, port);
            in = client.getInputStream();
            out = client.getOutputStream();
            if (!confirm()) {
                new MyDialog(frame, "連接服務器失敗", true).setVisible(true);
                return;
            }
            resetUI();
            frame.setTitle("五子棋 " + "已連接:" + name + " 的游戲:本機端口號:"
                    + client.getLocalPort());
            // 1,設置棋子顏色
            Config.setColor(Color.WHITE);
            // 2,交替下棋
            MyListener police = new MyListener();
            while (true) {
                if (flag) {
                    frame.addMouseListener(police);
                    while (Config.getX() == -1) {
                        Thread.sleep(20);
                    }
                    int x = Config.getX();
                    int y = Config.getY();
                    Config.clearNotify();
                    Graphics g = frame.getGraphics();
                    g.setColor(Config.getColor());
                    g.fillOval(x - (Config.SIZE / 2), y - (Config.SIZE / 2),
                            Config.SIZE - 5, Config.SIZE - 5);
                    // 將位置轉換為坐標并發送給服務器端
                    x = (x - Config.STARTX) / Config.SIZE;
                    y = (y - Config.STARTY) / Config.SIZE;
                    byte buf[] = new byte[2];
                    buf[0] = (byte) x;
                    buf[1] = (byte) y;
                    out.write(buf);
                    if (Config.isWin(Color.BLACK)) {
                        new MyDialog(frame, Color.BLACK).setVisible(true);
                    } else if (Config.isWin(Color.WHITE)) {
                        new MyDialog(frame, Color.WHITE).setVisible(true);
                    }
                    flag = !flag;
                    frame.removeMouseListener(police);
                } else {
                    byte[][] buf = new byte[Config.ROW + 1][Config.CLOUNM + 1];
                    for (int i = 0; i <= Config.ROW; i++) {
                        in.read(buf[i]);
                    }
                    Config.resetChess(buf);
                    frame.paint(frame.getGraphics());
                    if (Config.isWin(Color.BLACK)) {
                        new MyDialog(frame, Color.BLACK).setVisible(true);
                    } else if (Config.isWin(Color.WHITE)) {
                        new MyDialog(frame, Color.WHITE).setVisible(true);
                    }
                    flag = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            new MyDialog(frame, "連接服務器失敗", true).setVisible(true);
            return;
        }

    }
    public void threadDestory() throws Exception{
        in.close();
        out.close();
        client.close();
    }
    private void init() {
        String[][] initValue = new String[][] { { "IP地址:", "127.0.0.1" },
                { "端口:", "7777" } };
        // 創建創建賬號的對話框
        MyDialog initDialog = new MyDialog(frame, "請輸入對方地址", true, initValue);
        initDialog.setVisible(true);
        // 獲得輸入數據
        String[] nameAndPort = initDialog.getValue();
        if (nameAndPort == null) {
            return;
        }
        this.ip = nameAndPort[0];
        try {
            this.port = Integer.valueOf(nameAndPort[1]);
            // 判斷端口號是否正確
            if (port <= 0 || port > 65536) {
                String errMsg = "錯誤的端口號" + nameAndPort[1] + "。端口號必須在0和65536之間";
                JOptionPane.showMessageDialog(frame, errMsg, "錯誤的端口號",
                        JOptionPane.ERROR_MESSAGE);
                return;
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(frame, "輸入的端口號不是數字。", "錯誤的端口號",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        Config.setPort(port);
        Config.clearChess();
        frame.paint(frame.getGraphics());
    }
}

[文件] GameServer.java ~ 4KB     (13)    

package game;

import java.awt.Color;
import java.awt.Graphics;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import panel.Config;
import panel.MyListener;

public class GameServer implements Runnable {
    private ServerSocket server;
    private Socket client;
    private JFrame frame;
    private int port;
    private String name;
    private InputStream in;
    private OutputStream out;
    private boolean flag = true;

    public GameServer(JFrame frame) {
        this.frame = frame;
    }
    public void threadDestory() throws Exception{
        in.close();
        out.close();
        client.close();
        server.close();
    }
    /**
     * 確認連接
     */
    private void confirm() throws IOException {
        out.write(name.getBytes());
    }
    private void sendUI() throws IOException{
        String s=new String(Config.SIZE+"#"+Config.ROW+"#"+Config.CLOUNM);
        out.write(s.getBytes());
    }
    public void run() {
        init();
        try {
            server = new ServerSocket(Config.getPort());
            client = server.accept();
            in = client.getInputStream();
            out = client.getOutputStream();
            confirm();
            sendUI();
            // 設置棋子顏色
            Config.setColor(Color.BLACK);

            // 交替下棋
            MyListener police = new MyListener();
            Graphics g = frame.getGraphics();
            while (true) {
                if (flag) {
                    frame.addMouseListener(police);
                    while (Config.getX() == -1) {
                        Thread.sleep(20);
                    }
                    int x = Config.getX();
                    int y = Config.getY();
                    Config.clearNotify();
                    g.setColor(Config.getColor());
                    g.fillOval(x - (Config.SIZE / 2), y - (Config.SIZE / 2),
                            Config.SIZE - 5, Config.SIZE - 5);
                    // 發送棋盤給客戶端
                    byte[][] chess = Config.getChess();
                    for (int i = 0; i <= Config.ROW; i++) {
                        out.write(chess[i]);
                    }
                    if (Config.isWin(Color.BLACK)) {
                        new MyDialog(frame, Color.BLACK).setVisible(true);
                    } else if (Config.isWin(Color.WHITE)) {
                        new MyDialog(frame, Color.WHITE).setVisible(true);
                    }
                    flag = !flag;
                    frame.removeMouseListener(police);
                } else {
                    byte[] buf = new byte[2];
                    in.read(buf);
                    Config.isChessMan(buf[0], buf[1],
                            (Config.getColor() == Color.BLACK) ? Color.WHITE
                                    : Color.BLACK);
                    frame.paint(g);
                    if (Config.isWin(Color.BLACK)) {
                        new MyDialog(frame, Color.BLACK).setVisible(true);
                    } else if (Config.isWin(Color.WHITE)) {
                        new MyDialog(frame, Color.WHITE).setVisible(true);
                    }
                    flag = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            new MyDialog(frame, "客戶端已下線", true).setVisible(true);
            return;
        }
    }

    private void init() {
        String[][] initValue = new String[][] { { "用戶名:", "CJN" },
                { "端口:", "7777" } };
        MyDialog initDialog = new MyDialog(frame, "請輸入用戶名和端口", true, initValue);
        initDialog.setVisible(true);
        String[] nameAndPort = initDialog.getValue();
        if (nameAndPort == null) {
            return;
        }
        this.name = nameAndPort[0];
        try {
            this.port = Integer.valueOf(nameAndPort[1]);
            // 判斷端口號是否正確
            if (port <= 0 || port > 65536) {
                String errMsg = "錯誤的端口號" + nameAndPort[1] + "。端口號必須在0和65536之間";
                JOptionPane.showMessageDialog(frame, errMsg, "錯誤的端口號",
                        JOptionPane.ERROR_MESSAGE);
                return;
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(frame, "輸入的端口號不是數字。", "錯誤的端口號",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        Config.setPort(port);
        frame.setTitle("五子棋 " + "玩家: " + name + " 端口號:" + port);
        Config.clearChess();
        frame.paint(frame.getGraphics());
    }
}

[文件] MyDialog.java ~ 5KB     (11)    

package game;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import panel.Config;

/**
 * 本類用于添加建立相應的對話框
 * 
 * @author chenj_000
 *
 */
@SuppressWarnings("serial")
public class MyDialog extends JDialog implements ActionListener {
    static final int YES = 1, NO = 0;
    int message = -1;
    JButton yes, no;
    JFrame frame;
    private String context;
    /**
     * 需要添加進文本框的字符串數組初值
     */
    private String[][] items;
    /**
     * 根據傳入的字符串數組創建的文本框對象
     */
    private JTextField[] values;
    /**
     * 需要返回的文本框中的數據
     */
    private String[] retValues;

    /**
     * 該構造方法用以創建一個具有指定標題、所有者 Frame 和模式的對話框
     */
    public MyDialog(Frame owner, String title, boolean modal, String[][] items) {
        super(owner, title, modal);
        this.items = items;
        init();
    }

    /**
     * 設置提醒對話框
     */
    public MyDialog(JFrame j, String context, boolean flag) {
        super(j, "提醒", flag);
        frame = j;
        this.context = context;
        warn();
    }

    /**
     * 設置勝利對話框
     */
    public MyDialog(JFrame j, Color color) {
        super(j, "提示", true);
        frame = j;
        // Config.resetColor();
        win(color);
    }

    private void warn() {
        yes = new JButton("確定");
        no = new JButton("取消");
        yes.addActionListener(this);
        no.addActionListener(this);
        JPanel p1 = new JPanel();
        p1.add(new JLabel(context));
        JPanel p2 = new JPanel();
        p2.add(yes);
        p2.add(no);
        add(p1, BorderLayout.NORTH);
        add(p2, BorderLayout.CENTER);
        int x = (int) (frame.getBounds().x + 0.25 * frame.getBounds().width);
        int y = (int) (frame.getBounds().y + 0.25 * frame.getBounds().height);
        setBounds(x, y, 200, 110);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                message = -1;
                setVisible(false);
            }
        });
    }

    private void win(Color color) {
        yes = new JButton("確定");
        yes.addActionListener(this);
        JPanel p1 = new JPanel();
        String str = (Color.BLACK == color) ? "黑方勝利" : "白方勝利";
        p1.add(new JLabel(str));
        JPanel p2 = new JPanel();
        p2.add(yes);
        add(p1, BorderLayout.NORTH);
        add(p2, BorderLayout.CENTER);
        int x = (int) (frame.getBounds().x + 0.25 * frame.getBounds().width);
        int y = (int) (frame.getBounds().y + 0.25 * frame.getBounds().height);
        setBounds(x, y, 200, 110);
        Config.clearChess();
        Config.exchangeColor();
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                message = -1;
                setVisible(false);
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == yes) {
            message = YES;
            frame.paint(frame.getGraphics());
            setVisible(false);
        } else if (e.getSource() == no) {
            message = NO;
            frame.paint(frame.getGraphics());
            setVisible(false);
        }
    }

    /**
     * 初始化對話框布局
     */
    private void init() {
        Container container = this.getContentPane();
        container.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        int count = items.length;
        gbc.gridx = 0;
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.insets = new Insets(3, 3, 3, 3);
        for (int i = 0; i < count; i++) {
            gbc.gridy = i;
            container.add(new JLabel(items[i][0]), gbc);
        }
        values = new JTextField[count];
        gbc.gridx = 1;
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.weightx = 1.0;
        gbc.weighty = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        for (int i = 0; i < count; i++) {
            gbc.gridy = i;
            values[i] = new JTextField(items[i][1]);
            container.add(values[i], gbc);
        }
        gbc.gridx = 0;
        gbc.gridy = count;
        gbc.gridwidth = 2;
        gbc.gridheight = 1;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.SOUTH;
        container.add(new JSeparator(), gbc);
        gbc.gridy = count + 1;
        gbc.weightx = 1.0;
        gbc.weighty = 0;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.SOUTHEAST;
        gbc.insets = new Insets(7, 7, 7, 7);
        JButton btn = new JButton("確定");
        container.add(btn, gbc);
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                retValues = new String[items.length];
                for (int i = 0; i < retValues.length; i++) {
                    retValues[i] = values[i].getText();
                }
                // 釋放所有子組件所使用的所有本機屏幕資源
                MyDialog.this.dispose();
            }
        });
        this.setSize(300, count * 30 + 70);
        ChessUtils.locateDialogCenter(this);
    }

    /**
     * 獲取對話框中的所有數據
     */
    public String[] getValue() {
        return retValues;
    }
}
 本文由用戶 lai123 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!