1. 程式人生 > >Java小程式之你畫我猜

Java小程式之你畫我猜

package com.huaxin.client;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ClientUI extends JFrame {

	public JButton sendBtn;
	public JLabel contant;
	public JPanel drawPanel;
	public JPanel colorPanel;
	public JPanel waitPanel;
	public JPanel drawLeftPanel;
	public JPanel centerPanel;
	public JTextField jtf;
	public JTextArea jta;
	public Graphics2D g;
	public Color color;
	public ClientCtroller control;
	public Socket socket;
	public int x1, y1;
	public BasicStroke strock;
    public JComboBox<Integer> box;

	//初始化介面的時候開始建立客戶端物件
	public ClientUI() {
		try {
			socket = new Socket("localhost", 9090);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		ClientUI ui = new ClientUI();
		ui.initFrame();
	}

	public void initFrame() {

		this.setTitle("你畫我猜");
		this.setSize(700, 500);
		this.setDefaultCloseOperation(3);
		this.setLocationRelativeTo(null);
		// 總的面板
		// JPanel panel = new JPanel();
		// panel.setBackground(Color.red);
		// 等待面板
		waitPanel = new JPanel();
		waitPanel.setBackground(Color.red);
		JLabel label = new JLabel("正在為您尋找房間......");
		waitPanel.add(label);
		this.add(waitPanel);
		// 畫的面板
//		addDrawPanel();
//		addGuessPanel();
		this.setVisible(true);
		// 建立客戶端控制器物件
		control = new ClientCtroller(socket, this);
		control.dealwith();
	}

	//新增畫面板的函式
	public void addDrawPanel() {
		drawPanel = new JPanel();
		drawPanel.setLayout(new BorderLayout());
		// 畫面板的左右子面板
		drawLeftPanel = new JPanel();
		drawLeftPanel.setLayout(new BorderLayout());
		
		//左邊板的中間面板
		centerPanel = new JPanel();
		centerPanel.setBackground(Color.WHITE);
		//左面板下的顏色面板
		colorPanel = new JPanel();
		
		//給顏色面板設定空佈局
		colorPanel.setLayout(null);
		colorPanel.setBackground(Color.gray);
		colorPanel.setPreferredSize(new Dimension(0,60));
		
		//顏色面板的顏色按鈕
		Color [] colors={Color.red,Color.black,Color.orange,Color.green,
				Color.pink,Color.blue,Color.cyan,Color.magenta,Color.YELLOW};
		
		//顏色按鈕新增
		ActionListener btnlistener = new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				
				JButton bt =(JButton)e.getSource();
				color =bt.getBackground();
			}
		};
		for (int i = 0; i < colors.length; i++) {
			JButton btn = new JButton();
			btn.setBackground(colors[i]);
			btn.addActionListener(btnlistener);
			btn.setBounds(40+i*30, 15, 30, 30);
			colorPanel.add(btn);
		}
		
	
		//新增畫筆粗細
		box =new JComboBox<Integer>();
		box.setBounds(380, 15, 80, 30);
		for (int i = 0; i < 10; i++) {
			Integer intdata = new Integer(i+1);
			box.addItem(intdata);
		}
		colorPanel.add(box);
		
		JPanel drawRightPanel = new JPanel();

		drawRightPanel.setLayout(new BorderLayout());
		drawRightPanel.setPreferredSize(new Dimension(200, 0));
		// 右面板的的下面板
		JPanel buttonPanel = new JPanel();
		buttonPanel.setPreferredSize(new Dimension(0, 50));
		jta = new JTextArea();
		jta.setLineWrap(true);
		JScrollPane jsp = new JScrollPane(jta);
		jtf = new JTextField(11);
		contant = new JLabel();
		sendBtn = new JButton();
		sendBtn.setText("傳送");
		sendBtn.addActionListener(al);
		buttonPanel.add(jtf);
		buttonPanel.add(sendBtn);

		drawRightPanel.add(jsp);
		drawRightPanel.add(buttonPanel, BorderLayout.SOUTH);

		contant.setPreferredSize(new Dimension(0, 20));
		drawLeftPanel.add(contant, BorderLayout.NORTH);
		drawLeftPanel.add(centerPanel, BorderLayout.CENTER);
		drawLeftPanel.add(colorPanel, BorderLayout.SOUTH);
		drawPanel.add(drawLeftPanel);
		drawPanel.add(drawRightPanel, BorderLayout.EAST);
		this.add(drawPanel);
		centerPanel.addMouseListener(ma);
		centerPanel.addMouseMotionListener(ma);
		this.setVisible(true);
		g = (Graphics2D)centerPanel.getGraphics();
	}
	
	//新增猜面板的函式
	public void addGuessPanel() {
		contant.setText("猜的提示資訊");
		sendBtn.setEnabled(false);
		drawLeftPanel.remove(colorPanel);
		drawLeftPanel.repaint();
		this.setVisible(true);
	}

	//滑鼠監聽器
	MouseAdapter ma = new MouseAdapter() {
		
		public void mousePressed(MouseEvent e) {
			x1 = e.getX();
			y1 = e.getY();
		};
		
		public void mouseEntered(MouseEvent e) {
			if(color==null){
				color=Color.black;
			}
			
//			System.out.println(i);
			g.setColor(color);
			
		};

		public void mouseDragged(MouseEvent e) {
			int width=(int)box.getSelectedItem();
			strock = new BasicStroke(width);
			g.setStroke(strock);
			
			int x2 = e.getX();
			int y2 = e.getY();
			g.drawLine(x1, y1, x2, y2);
//			x1 = x2;
//			y1 = y2;
			try {
				
				control.sendMsg1(socket.getOutputStream(), x1, y1, x2, y2,g.getColor().getRGB(),width);
				x1 = x2;
				y1 = y2;
			} catch (IOException e1) {
			}
		};
		
	};
	
	//傳送監聽器
	ActionListener al =new ActionListener() {
		
		public void actionPerformed(ActionEvent e) {
			//獲取傳送框的內容
			String str = jtf.getText();
			if(str==null || str.equals("")){
				JOptionPane.showMessageDialog(null, "傳送內容不能為空!");
			}else{
				try {
				control.dos.writeUTF(str);
				jtf.setText("");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
				
		}
	};

}

package com.huaxin.client;

import java.awt.BasicStroke;
import java.awt.Color;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

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

public class ClientCtroller {

	public Socket socket;
	public ClientUI ui;

	public DataInputStream dis;
	public DataOutputStream dos;
	
//	public ClientCtroller(Socket socket) {
//		this.socket=socket;
//	}
//	
	public ClientCtroller(Socket socket, JFrame ui) {
		this.socket = socket;
		this.ui =(ClientUI) ui;
	}

	public void dealwith() {
		try {
			InputStream ins =this.socket.getInputStream();
			OutputStream ous =this.socket.getOutputStream();
			dis=new DataInputStream(ins);
			dos = new DataOutputStream(ous);
			String msg = readMsg(socket.getInputStream());
			
			if ("draw".equals(msg)) {
				// 如果是draw,則客戶端顯示畫的介面
				ui.remove(ui.waitPanel);
				ui.addDrawPanel();
				ui.sendBtn.setEnabled(false);
				ui.repaint();
//				System.out.println("draw介面完畢比");
				//接收要畫的資訊
				String drawinfo=dis.readUTF();
				//將要畫的資訊新增到面板上
				ui.contant.setText("畫的東西為:"+drawinfo);
				
				while(true){
					String s=readMsg(ins);
					System.out.println("draw 接受到的資訊:"+s);
//					System.out.println(s);
					//接收伺服器端傳送的猜的客戶端猜的訊息
					if(!"data".equals(s)){
						String s1=dis.readUTF();
						System.out.println("s1:"+s);
						//如果猜對了,則在畫的客戶端顯示猜對了
						if("yes".equals(s1)){
//							JOptionPane.showMessageDialog(null, "你猜對了!");
							ui.jta.append("對方猜對了"+"\r\n");
						}
					//否則畫的客戶端顯示猜的客戶單端的訊息
						else{
							ui.jta.append(s1+"\r\n");
						}
					}
				}
			}
			if ("guess".equals(msg)) {
				// 如果是猜,則顯示猜的客戶端
				String guessinfo=dis.readUTF();
				ui.remove(ui.waitPanel);
				ui.addDrawPanel();
				ui.addGuessPanel();
				ui.contant.setText(guessinfo);
				ui.sendBtn.setEnabled(true);
//				ui.repaint();
//				System.out.println("guess介面完畢比");
				while(true){
					//接收伺服器端的資料
					String info =readMsg(ins);
					//如果是資料訊息
//					System.out.println("猜客戶端接收的訊息為:"+info);
					if("data".equals(info)){
						readMsg1(socket.getInputStream());
					}
					//如果是自己傳送的猜的訊息
					else if("msg".equals(info)){
						//再次讀取一條訊息
						String info2=dis.readUTF();
						System.out.println("info2"+info2);
						if("yes".equals(info2)){
							info2=dis.readUTF();
							ui.jta.append(info2+"\r\n");
							ui.jta.append("恭喜你猜對了......");
						}
						else{
							System.out.println("接收到的資訊為:"+info2);
							ui.jta.append(info2+"\r\n");
						}
					}
//						else{
//						String info3=dis.readUTF();
//					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 傳送訊息的函式
	public void sendMsg(OutputStream os, String s) throws IOException {

		// 向客戶端輸出資訊
		//
		// System.out.println(s);
		byte[] bytes = s.getBytes();
		os.write(bytes);
		os.write(13);
		os.write(10);
		os.flush();

	}

	// 讀取客戶端輸入資料的函式
	public String readMsg(InputStream ins) throws Exception {
		// 讀取客戶端的資訊
		int value = ins.read();
		// 讀取整行 讀取到回車(13)換行(10)時停止讀
		String str = "";
		while (value != 10) {
			// 點選關閉客戶端時會返回-1值
			if (value == -1) {
				throw new Exception();
			}
			str = str + ((char) value);
			value = ins.read();
		}
		str = str.trim();
		return str;
	}

	// 傳送訊息的函式
	public void sendMsg1(OutputStream os, int x1, int y1, int x2, int y2,int color,int width) throws IOException {

		DataOutputStream dos = new DataOutputStream(os);
//		dos.writeUTF("data");
		dos.writeInt(x1); 
		dos.writeInt(y1);
		dos.writeInt(x2);
		dos.writeInt(y2);
		dos.writeInt(color);
		dos.writeInt(width);
		dos.flush();

	}
	
	public void readMsg1(InputStream is) throws IOException {

		DataInputStream dis = new DataInputStream (is);
		int x1=dis.readInt();
		int y1=dis.readInt();
		int x2=dis.readInt();
		int y2=dis.readInt();
		int color =dis.readInt();
		int width=dis.readInt();
		Color c =new Color(color);
		BasicStroke strock = new BasicStroke(width);
		ui.g.setColor(c);
		ui.g.setStroke(strock);
//		System.out.println("ui:"+ui);
		ui.g.drawLine(x1, y1, x2, y2);
//		System.out.println("x1:"+x1+"y1:"+y1+"x2:"+x2+"y2:"+y2);

	}

}

package com.huaxin.client;

public class ClientTest {
	
	public static void main(String[] args) {
		ClientUI ui = new ClientUI();
		ui.initFrame();
	}
}

五、專案執行結果: