📄 clientform.java
字号:
\\ClientForm.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.rmi.*;
import java.rmi.server.*;
public class ClientForm extends JFrame
{
private ChatViewer chat;
private JTextField msgeditor;
private JButton msgsender;
private Container contentpane;
private JPanel panel;
private ServerForChatInterface server;
public ClientForm(String serveraddress,int port)
{
super("简易聊天室");
System.out.println("connect to server...");
try{
this.server = (ServerForChatInterface)Naming.lookup("rmi://"+serveraddress+":"+port+"/ChatServer");
}catch(Exception e){
System.out.println("不能连接到服务器.");
System.exit(0);
}
this.initializedComponent();
this.fireEvent();
this.registChatViewer();
}
private void initializedComponent()
{
this.chat = new ChatViewer("<font color='blue'>欢迎进入聊天室</font>");
this.msgeditor = new JTextField();
this.msgsender = new JButton("发送");
this.panel = new JPanel();
this.panel.setLayout(new BorderLayout());
this.panel.add(this.msgeditor,BorderLayout.CENTER);
this.panel.add(this.msgsender,BorderLayout.EAST);
this.contentpane = this.getContentPane();
this.contentpane.setLayout(new BorderLayout());
this.contentpane.add(this.chat,BorderLayout.CENTER);
this.contentpane.add(this.panel,BorderLayout.SOUTH);
this.setSize(600,400);
this.setVisible(true);
}
private void fireEvent()
{
MessageSender ms = new MessageSender();
this.msgeditor.addActionListener(ms);
this.msgsender.addActionListener(ms);
this.msgeditor.grabFocus();
}
private void chat()
{
String msg = this.msgeditor.getText();
this.msgeditor.setText("");
try{
this.server.chat(msg);
}catch(Exception e){
this.chat.appendChatContent("<font color='red'><b>发送消息失败,请检查网络.</b></font>");
}
}
private void registChatViewer()
{
try{
UnicastRemoteObject.exportObject((ChatViewerInterface)(this.chat));
this.server.regist((ChatViewerInterface)(this.chat));
}catch(Exception e){
this.chat.appendChatContent("<font color='red'><b>连接服务器失败,请检查网络.</b></font>");
}
}
class MessageSender implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
chat();
}
}
public static void main(String args[])
{
String serveraddress = "127.0.0.1";
int port = 1099;
if(args!=null&&args.length==2)
{
serveraddress = args[0];
try{
port = Integer.parseInt(args[1]);
}catch(Exception e){}
}
ClientForm client = new ClientForm(serveraddress,port);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -