//为服务菜单栏设置热键'V'
serviceMenu.setMnemonic('V');
部分热键设置略
}
/**
* 程序初始化函数
*/
public void init(){
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//添加菜单栏
serviceMenu.add (portItem);
serviceMenu.add (startItem);
serviceMenu.add (stopItem);
serviceMenu.add (exitItem);
jMenuBar.add (serviceMenu);
helpMenu.add (helpItem);
jMenuBar.add (helpMenu);
setJMenuBar (jMenuBar);
//初始化按钮
portSet = new JButton("端口设置");
startServer = new JButton("启动服务");
stopServer = new JButton("停止服务" );
exitButton = new JButton("退出" );
//将按钮添加到工具栏
toolBar.add(portSet);
toolBar.addSeparator();//添加分隔栏
toolBar.add(startServer);
toolBar.add(stopServer);
toolBar.addSeparator();//添加分隔栏
toolBar.add(exitButton);
contentPane.add(toolBar,BorderLayout.NORTH);
//初始时,令停止服务按钮不可用
stopServer.setEnabled(false);
stopItem .setEnabled(false);
//为菜单栏添加事件监听
portItem.addActionListener(this);
startItem.addActionListener(this);
stopItem.addActionListener(this);
exitItem.addActionListener(this);
helpItem.addActionListener(this);
//添加按钮的事件侦听
portSet.addActionListener(this);
startServer.addActionListener(this);
stopServer.addActionListener(this);
exitButton.addActionListener(this);
combobox = new JComboBox();
combobox.insertItemAt("所有人",0);
combobox.setSelectedIndex(0);
messageShow = new JTextArea();
//关闭程序时的操作
this.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){
stopService();
System.exit(0);
}
}
);
}
/**
* 事件处理
*/
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj == startServer || obj == startItem) { //启动服务端
startService();
}
else if (obj == stopServer || obj == stopItem) { //停止服务端
int j=JOptionPane.showConfirmDialog(
this,"真的停止服务吗?","停止服务",
JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE);
if (j == JOptionPane.YES_OPTION){
stopService();
}
}
else if (obj == portSet || obj == portItem) { //端口设置
//调出端口设置的对话框
PortConf portConf = new PortConf(this);
portConf.show();
}
else if (obj == exitButton || obj == exitItem) { //退出程序
int j=JOptionPane.showConfirmDialog(
this,"真的要退出吗?","退出",
JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE);
if (j == JOptionPane.YES_OPTION){
stopService();
System.exit(0);
}
}
else if (obj == helpItem) { //菜单栏中的帮助
//调出帮助对话框
Help helpDialog = new Help(this);
helpDialog.show();
}
else if (obj == sysMessage || obj == sysMessageButton) { //发送系统消息
sendSystemMessage();
}
}
/**
* 启动服务端
*/
public void startService(){
try{
serverSocket = new ServerSocket(port,10);
messageShow.append("服务端已经启动,在"+port+"端口侦听...\n");
startServer.setEnabled(false);
startItem.setEnabled(false);
portSet.setEnabled(false);
portItem.setEnabled(false);
stopServer .setEnabled(true);
stopItem .setEnabled(true);
sysMessage.setEnabled(true);
}
catch (Exception e){
//System.out.println(e);
}
userLinkList = new UserLinkList();
listenThread = new ServerListen(serverSocket,combobox,
messageShow,showStatus,userLinkList);
listenThread.start();
}
本文过长,分成一下几部分:
Leave a reply