?? chatclient.java
字號:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.net.*;
/*
* 聊天客戶端的主框架類
*/
public class ChatClient extends JFrame implements ActionListener{
String ip = "127.0.0.1";//連接到服務端的ip地址
int port = 8888;//連接到服務端的端口號
String userName = "匆匆過客";//用戶名
int type = 0;//0表示未連接,1表示已連接
Image icon;//程序圖標
JComboBox combobox;//選擇發送消息的接受者
JTextArea messageShow;//客戶端的信息顯示
JScrollPane messageScrollPane;//信息顯示的滾動條
JLabel express,sendToLabel,messageLabel ;
JTextField clientMessage;//客戶端消息的發送
JCheckBox checkbox;//悄悄話
JComboBox actionlist;//表情選擇
JButton clientMessageButton;//發送消息
JTextField showStatus;//顯示用戶連接狀態
Socket socket;
ObjectOutputStream output;//網絡套接字輸出流
ObjectInputStream input;//網絡套接字輸入流
ClientReceive recvThread;
//建立菜單欄
JMenuBar jMenuBar = new JMenuBar();
//建立菜單組
JMenu operateMenu = new JMenu ("操作(O)");
//建立菜單項
JMenuItem loginItem = new JMenuItem ("用戶登錄(I)");
JMenuItem logoffItem = new JMenuItem ("用戶注銷(L)");
JMenuItem exitItem=new JMenuItem ("退出(X)");
JMenu conMenu=new JMenu ("設置(C)");
JMenuItem userItem=new JMenuItem ("用戶設置(U)");
JMenuItem connectItem=new JMenuItem ("連接設置(C)");
JMenu helpMenu=new JMenu ("幫助(H)");
JMenuItem helpItem=new JMenuItem ("幫助(H)");
//建立工具欄
JToolBar toolBar = new JToolBar();
//建立工具欄中的按鈕組件
JButton loginButton;//用戶登錄
JButton logoffButton;//用戶注銷
JButton userButton;//用戶信息的設置
JButton connectButton;//連接設置
JButton exitButton;//退出按鈕
//框架的大小
Dimension faceSize = new Dimension(400, 600);
JPanel downPanel ;
GridBagLayout girdBag;
GridBagConstraints girdBagCon;
public ChatClient(){
init();//初始化程序
//添加框架的關閉事件處理
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
//設置框架的大小
this.setSize(faceSize);
//設置運行時窗口的位置
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation( (int) (screenSize.width - faceSize.getWidth()) / 2,
(int) (screenSize.height - faceSize.getHeight()) / 2);
this.setResizable(false);
this.setTitle("聊天室客戶端"); //設置標題
//程序圖標
icon = getImage("icon.gif");
this.setIconImage(icon); //設置程序圖標
show();
//為操作菜單欄設置熱鍵'V'
operateMenu.setMnemonic('O');
//為用戶登錄設置快捷鍵為ctrl+i
loginItem.setMnemonic ('I');
loginItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_I,InputEvent.CTRL_MASK));
//為用戶注銷快捷鍵為ctrl+l
logoffItem.setMnemonic ('L');
logoffItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_L,InputEvent.CTRL_MASK));
//為退出快捷鍵為ctrl+x
exitItem.setMnemonic ('X');
exitItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_X,InputEvent.CTRL_MASK));
//為設置菜單欄設置熱鍵'C'
conMenu.setMnemonic('C');
//為用戶設置設置快捷鍵為ctrl+u
userItem.setMnemonic ('U');
userItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_U,InputEvent.CTRL_MASK));
//為連接設置設置快捷鍵為ctrl+c
connectItem.setMnemonic ('C');
connectItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_C,InputEvent.CTRL_MASK));
//為幫助菜單欄設置熱鍵'H'
helpMenu.setMnemonic('H');
//為幫助設置快捷鍵為ctrl+p
helpItem.setMnemonic ('H');
helpItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_H,InputEvent.CTRL_MASK));
}
/**
* 程序初始化函數
*/
public void init(){
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//添加菜單欄
operateMenu.add (loginItem);
operateMenu.add (logoffItem);
operateMenu.add (exitItem);
jMenuBar.add (operateMenu);
conMenu.add (userItem);
conMenu.add (connectItem);
jMenuBar.add (conMenu);
helpMenu.add (helpItem);
jMenuBar.add (helpMenu);
setJMenuBar (jMenuBar);
//初始化按鈕
loginButton = new JButton("登錄");
logoffButton = new JButton("注銷");
userButton = new JButton("用戶設置" );
connectButton = new JButton("連接設置" );
exitButton = new JButton("退出" );
//當鼠標放上顯示信息
loginButton.setToolTipText("連接到指定的服務器");
logoffButton.setToolTipText("與服務器斷開連接");
userButton.setToolTipText("設置用戶信息");
connectButton.setToolTipText("設置所要連接到的服務器信息");
//將按鈕添加到工具欄
toolBar.add(userButton);
toolBar.add(connectButton);
toolBar.addSeparator();//添加分隔欄
toolBar.add(loginButton);
toolBar.add(logoffButton);
toolBar.addSeparator();//添加分隔欄
toolBar.add(exitButton);
contentPane.add(toolBar,BorderLayout.NORTH);
checkbox = new JCheckBox("悄悄話");
checkbox.setSelected(false);
actionlist = new JComboBox();
actionlist.addItem("微笑地");
actionlist.addItem("高興地");
actionlist.addItem("輕輕地");
actionlist.addItem("生氣地");
actionlist.addItem("小心地");
actionlist.addItem("靜靜地");
actionlist.setSelectedIndex(0);
//初始時
loginButton.setEnabled(true);
logoffButton.setEnabled(false);
//為菜單欄添加事件監聽
loginItem.addActionListener(this);
logoffItem.addActionListener(this);
exitItem.addActionListener(this);
userItem.addActionListener(this);
connectItem.addActionListener(this);
helpItem.addActionListener(this);
//添加按鈕的事件偵聽
loginButton.addActionListener(this);
logoffButton.addActionListener(this);
userButton.addActionListener(this);
connectButton.addActionListener(this);
exitButton.addActionListener(this);
combobox = new JComboBox();
combobox.insertItemAt("所有人",0);
combobox.setSelectedIndex(0);
messageShow = new JTextArea();
messageShow.setEditable(false);
//添加滾動條
messageScrollPane = new JScrollPane(messageShow,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
messageScrollPane.setPreferredSize(new Dimension(400,400));
messageScrollPane.revalidate();
clientMessage = new JTextField(23);
clientMessage.setEnabled(false);
clientMessageButton = new JButton();
clientMessageButton.setText("發送");
//添加系統消息的事件偵聽
clientMessage.addActionListener(this);
clientMessageButton.addActionListener(this);
sendToLabel = new JLabel("發送至:");
express = new JLabel(" 表情: ");
messageLabel = new JLabel("發送消息:");
downPanel = new JPanel();
girdBag = new GridBagLayout();
downPanel.setLayout(girdBag);
girdBagCon = new GridBagConstraints();
girdBagCon.gridx = 0;
girdBagCon.gridy = 0;
girdBagCon.gridwidth = 5;
girdBagCon.gridheight = 2;
girdBagCon.ipadx = 5;
girdBagCon.ipady = 5;
JLabel none = new JLabel(" ");
girdBag.setConstraints(none,girdBagCon);
downPanel.add(none);
girdBagCon = new GridBagConstraints();
girdBagCon.gridx = 0;
girdBagCon.gridy = 2;
girdBagCon.insets = new Insets(1,0,0,0);
//girdBagCon.ipadx = 5;
//girdBagCon.ipady = 5;
girdBag.setConstraints(sendToLabel,girdBagCon);
downPanel.add(sendToLabel);
girdBagCon = new GridBagConstraints();
girdBagCon.gridx =1;
girdBagCon.gridy = 2;
girdBagCon.anchor = GridBagConstraints.LINE_START;
girdBag.setConstraints(combobox,girdBagCon);
downPanel.add(combobox);
girdBagCon = new GridBagConstraints();
girdBagCon.gridx =2;
girdBagCon.gridy = 2;
girdBagCon.anchor = GridBagConstraints.LINE_END;
girdBag.setConstraints(express,girdBagCon);
downPanel.add(express);
girdBagCon = new GridBagConstraints();
girdBagCon.gridx = 3;
girdBagCon.gridy = 2;
girdBagCon.anchor = GridBagConstraints.LINE_START;
//girdBagCon.insets = new Insets(1,0,0,0);
//girdBagCon.ipadx = 5;
//girdBagCon.ipady = 5;
girdBag.setConstraints(actionlist,girdBagCon);
downPanel.add(actionlist);
girdBagCon = new GridBagConstraints();
girdBagCon.gridx = 4;
girdBagCon.gridy = 2;
girdBagCon.insets = new Insets(1,0,0,0);
//girdBagCon.ipadx = 5;
//girdBagCon.ipady = 5;
girdBag.setConstraints(checkbox,girdBagCon);
downPanel.add(checkbox);
girdBagCon = new GridBagConstraints();
girdBagCon.gridx = 0;
girdBagCon.gridy = 3;
girdBag.setConstraints(messageLabel,girdBagCon);
downPanel.add(messageLabel);
girdBagCon = new GridBagConstraints();
girdBagCon.gridx = 1;
girdBagCon.gridy = 3;
girdBagCon.gridwidth = 3;
girdBagCon.gridheight = 1;
girdBag.setConstraints(clientMessage,girdBagCon);
downPanel.add(clientMessage);
girdBagCon = new GridBagConstraints();
girdBagCon.gridx = 4;
girdBagCon.gridy = 3;
girdBag.setConstraints(clientMessageButton,girdBagCon);
downPanel.add(clientMessageButton);
showStatus = new JTextField(35);
showStatus.setEditable(false);
girdBagCon = new GridBagConstraints();
girdBagCon.gridx = 0;
girdBagCon.gridy = 5;
girdBagCon.gridwidth = 5;
girdBag.setConstraints(showStatus,girdBagCon);
downPanel.add(showStatus);
contentPane.add(messageScrollPane,BorderLayout.CENTER);
contentPane.add(downPanel,BorderLayout.SOUTH);
//關閉程序時的操作
this.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){
if(type == 1){
DisConnect();
}
System.exit(0);
}
}
);
}
/**
* 事件處理
*/
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj == userItem || obj == userButton) { //用戶信息設置
//調出用戶信息設置對話框
UserConf userConf = new UserConf(this,userName);
userConf.show();
userName = userConf.userInputName;
}
else if (obj == connectItem || obj == connectButton) { //連接服務端設置
//調出連接設置對話框
ConnectConf conConf = new ConnectConf(this,ip,port);
conConf.show();
ip = conConf.userInputIp;
port = conConf.userInputPort;
}
else if (obj == loginItem || obj == loginButton) { //登錄
Connect();
}
else if (obj == logoffItem || obj == logoffButton) { //注銷
DisConnect();
showStatus.setText("");
}
else if (obj == clientMessage || obj == clientMessageButton) { //發送消息
SendMessage();
clientMessage.setText("");
}
else if (obj == exitButton || obj == exitItem) { //退出
int j=JOptionPane.showConfirmDialog(
this,"真的要退出嗎?","退出",
JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE);
if (j == JOptionPane.YES_OPTION){
if(type == 1){
DisConnect();
}
System.exit(0);
}
}
else if (obj == helpItem) { //菜單欄中的幫助
//調出幫助對話框
Help helpDialog = new Help(this);
helpDialog.show();
}
}
public void Connect(){
try{
socket = new Socket(ip,port);
}
catch (Exception e){
JOptionPane.showConfirmDialog(
this,"不能連接到指定的服務器。\n請確認連接設置是否正確。","提示",
JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE);
return;
}
try{
output = new ObjectOutputStream(socket.getOutputStream());
output.flush();
input = new ObjectInputStream(socket.getInputStream() );
output.writeObject(userName);
output.flush();
recvThread = new ClientReceive(socket,output,input,combobox,messageShow,showStatus);
recvThread.start();
loginButton.setEnabled(false);
loginItem.setEnabled(false);
userButton.setEnabled(false);
userItem.setEnabled(false);
connectButton.setEnabled(false);
connectItem.setEnabled(false);
logoffButton.setEnabled(true);
logoffItem.setEnabled(true);
clientMessage.setEnabled(true);
messageShow.append("連接服務器 "+ip+":"+port+" 成功...\n");
type = 1;//標志位設為已連接
}
catch (Exception e){
System.out.println(e);
return;
}
}
public void DisConnect(){
loginButton.setEnabled(true);
loginItem.setEnabled(true);
userButton.setEnabled(true);
userItem.setEnabled(true);
connectButton.setEnabled(true);
connectItem.setEnabled(true);
logoffButton.setEnabled(false);
logoffItem.setEnabled(false);
clientMessage.setEnabled(false);
if(socket.isClosed()){
return ;
}
try{
output.writeObject("用戶下線");
output.flush();
input.close();
output.close();
socket.close();
messageShow.append("已經與服務器斷開連接...\n");
type = 0;//標志位設為未連接
}
catch (Exception e){
//
}
}
public void SendMessage(){
String toSomebody = combobox.getSelectedItem().toString();
String status = "";
if(checkbox.isSelected()){
status = "悄悄話";
}
String action = actionlist.getSelectedItem().toString();
String message = clientMessage.getText();
if(socket.isClosed()){
return ;
}
try{
output.writeObject("聊天信息");
output.flush();
output.writeObject(toSomebody);
output.flush();
output.writeObject(status);
output.flush();
output.writeObject(action);
output.flush();
output.writeObject(message);
output.flush();
}
catch (Exception e){
//
}
}
/**
* 通過給定的文件名獲得圖像
*/
Image getImage(String filename) {
URLClassLoader urlLoader = (URLClassLoader)this.getClass().
getClassLoader();
URL url = null;
Image image = null;
url = urlLoader.findResource(filename);
image = Toolkit.getDefaultToolkit().getImage(url);
MediaTracker mediatracker = new MediaTracker(this);
try {
mediatracker.addImage(image, 0);
mediatracker.waitForID(0);
}
catch (InterruptedException _ex) {
image = null;
}
if (mediatracker.isErrorID(0)) {
image = null;
}
return image;
}
public static void main(String[] args) {
ChatClient app = new ChatClient();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -