java实现联机五子棋

lai123的头像 lai123 0 2016-01-30 13:50 0

 基本信息

× 1   

浏览数: 2100

分享时间: 2 年 前

3

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;
	/**
	 * ¾ÝÉϱ߿ò¾àÀë
	 */
	public static final int STARTY = 90;
	/**
	 * ¼ä¸ô
	 */
	public static int SIZE = 50;
	/**
	 * ÐÐÊý
	 */
	public static int ROW = 10;
	/**
	 * ÁÐÊý
	 */
	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;
	}

	/**
	 * ÅжÏÊó±êËùµã»÷λÖÃÊÇ·ñ¿ÉÏÂÆå×Ó
	 */
	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;
		}
	}

	/**
	 * ÅжÏÊó±êËùµã»÷×ø±êÊÇ·ñ¿ÉÏÂÆå×Ó
	 */
	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;
	}

	/**
	 * ÅжÏÊÇ·ñʤÀû
	 */
	public static boolean isWin(Color color) {
		boolean flag = false;
		int n = 0;
		int c = (color == Color.BLACK) ? 1 : -1;
		// ÅжÏÁÐ
		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;
		// ÅжÏÐÐ
		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;
		// ÅжÏ×óб
		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;
		// ÅжÏÓÒб
		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;
	}

	/**
	 * ÉèÖö˿ںÅ
	 */
	public static void setPort(int p) {
		port = p;
		// System.out.println(port);
	}

	/**
	 * »ñÈ¡¶Ë¿ÚºÅ
	 */
	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;
	}
}

  • huyuyang的头像 huyuyang 2017-06-19 18:33 代码数:0

    咋注释乱码的代码都贴上来了~

您的评论: