📄 baseclient.java
字号:
/*********************
Base class for client
*********************/
package chat;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DateFormat;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.event.*;
public class BaseClient extends JPanel
{
public final static String USER_SETTING = "setting.txt";
public final static String ADMIN_LOG = "log.txt";
protected JList messageList, userList;
protected DefaultListModel listModel, userModel;
protected JTextField messageField;
protected JMenu fileMenu,viewsMenu,optionsMenu,helpMenu,optionsAdminMenu;
protected JMenuItem fm3,vm4,om2,om3,hm1;//fm1,fm2,
protected JRadioButtonMenuItem vm1,vm2,vm3;
protected JCheckBoxMenuItem om1;
protected JButton sendButton,sendPrivateButton,exitButton;
protected JScrollPane scrollPane,scrollUser;
protected JPanel commandPanel;
protected JMenuBar menuBar;
protected ChatServer server;
protected String userid;
public static ClientSetting settings;
public BaseClient()
{
buildLayout();
}
public BaseClient(String user, ChatServer s)
{
this();
userid = user;
server = s;
}
protected void buildLayout()
{
final ImageIcon icon = new ImageIcon("pics/face.gif");
sendButton = new JButton("Send to all",icon);
sendPrivateButton = new JButton("Send Private");
exitButton = new JButton("Exit");
sendButton.setToolTipText("Click to send your message to all.");
sendPrivateButton.setToolTipText("Click to send your message to selected user only.");
exitButton.setToolTipText("Click to exit chat.");
setLayout(new BorderLayout());
listModel = new DefaultListModel();
messageList = new JList(listModel);
scrollPane = new JScrollPane(messageList);
add(scrollPane, BorderLayout.CENTER);
userModel = new DefaultListModel();
userList = new JList(userModel);
userList.setFixedCellWidth(100);
scrollUser = new JScrollPane(userList);
add(scrollUser, BorderLayout.EAST);
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == sendButton)
{
String message = messageField.getText();
try
{
server.broadcastMessage(userid + ": " + message);
}catch (Exception e){};
messageField.setText("");
}
else if (event.getSource() == sendPrivateButton)
{
if (userList.getSelectedValue()!=null)
{
String message = messageField.getText();
try{
server.broadcastMessage("!user " + ((String)userList.getSelectedValue()).trim() + " " + userid + ": " + message);
}catch (Exception e){};
}
else
JOptionPane.showMessageDialog(null,"Please select a user to send private message", "Notice",JOptionPane.INFORMATION_MESSAGE);
messageField.setText("");
}
else if (event.getSource() == exitButton)
{
try{
server.broadcastRemovedUser(userid);
saveUserSetting();
System.exit(0);
}catch (Exception e){};
}
}
};
commandPanel = new JPanel();
messageField = new JTextField(20);
messageField.addActionListener(listener);
commandPanel.add(messageField);
sendButton.addActionListener(listener);
commandPanel.add(sendButton);
sendPrivateButton.addActionListener(listener);
commandPanel.add(sendPrivateButton);
exitButton.addActionListener(listener);
commandPanel.add(exitButton);
add(commandPanel, BorderLayout.SOUTH);
}
public static void getUserSetting() throws IOException
{
String temp;
settings = new ClientSetting();
File f = new File(USER_SETTING);
if (!(f.exists()))
{
System.out.println("File does not exists!");
return;
}
FileReader fileReader = new FileReader(f);
BufferedReader reader = new BufferedReader(fileReader);
String fileText = reader.readLine();
while (fileText != null)
{
int index = fileText.indexOf('=');
if (index != -1) // <- Any line without '=' will be comments
{
if (fileText.substring(0, index).compareTo("look") == 0)
{
settings.look = fileText.substring(index + 1);
}
else if (fileText.substring(0, index).compareTo("logsize") == 0)
{
temp = fileText.substring(index + 1);
settings.logSize = Integer.parseInt(temp);
}
else if (fileText.substring(0, index).compareTo("history") == 0)
{
temp = fileText.substring(index + 1);
settings.history = (temp.compareTo("true") == 0 ? true : false);
}
}
fileText = reader.readLine();
}
reader.close();
}
public void getLog() throws IOException
{
File f = new File(ADMIN_LOG);
if (!(f.exists()))
{
System.out.println("File does not exists!");
return;
}
FileReader fileReader = new FileReader(f);
BufferedReader reader = new BufferedReader(fileReader);
String fileText = reader.readLine();
listModel.clear();
listModel.addElement("\n");
listModel.addElement("-------- Start of Log File -------");
while (fileText != null)
{
listModel.addElement(fileText);
fileText = reader.readLine();
}
listModel.addElement("--------- End of Log File --------");
listModel.addElement("\n");
reader.close();
}
public void clearLog() throws IOException
{
String temp;
FileWriter fileWriter = new FileWriter(ADMIN_LOG,false);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.close();
listModel.addElement("-------- Log file cleared --------");
}
public static void saveUserSetting() throws IOException
{
String temp;
FileWriter fileWriter = new FileWriter(USER_SETTING,false);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("logsize="+String.valueOf(settings.logSize));
writer.newLine();
writer.write("look="+settings.look);
writer.newLine();
writer.write("history="+String.valueOf(settings.history));
writer.close();
}
public void displayMessage(ChatMessage message)
{
String line;
//JLabel lblLine;
DateFormat formatter = DateFormat.getTimeInstance(DateFormat.SHORT);
java.util.Date msgDate = message.messageDate;
String msgText = message.messageText;
if (msgText.substring(0,5).compareToIgnoreCase("!exit")==0)
{
line = msgText.substring(6);
listModel.addElement(line);
}
else if (msgText.substring(0,5).compareToIgnoreCase("!user")==0)
{
if (msgText.indexOf(userid)!=-1)
{
line = msgText.substring(msgText.indexOf(userid) + userid.length() + 1);
line = "(" + formatter.format(msgDate) + ") " + "Private msg -> " + line;
listModel.addElement(line);
}
}
else
{
line = "(" + formatter.format(msgDate) + ") " + msgText;
listModel.addElement(line);
}
int count = listModel.getSize();
messageList.ensureIndexIsVisible(count - 1);
}
public void clearUser() throws Exception
{
userModel.clear();
}
public void addUser(String user) throws Exception
{
userModel.addElement(user);
int count = userModel.getSize();
userList.ensureIndexIsVisible(count - 1);
}
public void removeUser(String id) throws Exception
{
userModel.removeElement(id);
}
public void displayHistory() throws Exception
{
ChatMessage[] messages = server.getHistory();
for (int i =0; i < messages.length; i++)
{
displayMessage(messages[i]);
}
}
public class ClientMenu extends JFrame
{
public ClientMenu(String txt)
{
super(txt);
Container contentPane = getContentPane();
Font f10 = new Font("SansSerif", Font.PLAIN, 10);
Dimension dim = new Dimension(0, 10);
/**** File Menu ****/
fileMenu = new JMenu("File");
MenuItemMonitor menuItemMonitor = new MenuItemMonitor();
fm3 = new JMenuItem("Exit");
fm3.addActionListener(menuItemMonitor);
fileMenu.add(fm3);
/**** Views menu ****/
viewsMenu = new JMenu("Views");
vm1 = new JRadioButtonMenuItem("Metal");
vm2 = new JRadioButtonMenuItem("Window");
vm3 = new JRadioButtonMenuItem("Motif");
vm4 = new JMenuItem("Clear Chat");
if (settings.look.compareTo("Metal")==0)
vm1.setSelected(true);
else if (settings.look.compareTo("Window")==0)
vm2.setSelected(true);
else if (settings.look.compareTo("Motif")==0)
vm3.setSelected(true);
ButtonGroup bg = new ButtonGroup();
bg.add(vm1);
bg.add(vm2);
bg.add(vm3);
vm1.addActionListener(menuItemMonitor);
vm2.addActionListener(menuItemMonitor);
vm3.addActionListener(menuItemMonitor);
vm4.addActionListener(menuItemMonitor);
viewsMenu.add(vm1);
viewsMenu.add(vm2);
viewsMenu.add(vm3);
viewsMenu.addSeparator();
viewsMenu.add(vm4);
/**** Options Menu ****/
optionsMenu = new JMenu("Options");
om1 = new JCheckBoxMenuItem("History");
om2 = new JMenuItem("View Log");
om3 = new JMenuItem("Clear Log");
optionsAdminMenu = new JMenu("Admin");
if (settings.history == true)
om1.setSelected(true);
if (userid.compareToIgnoreCase("Admin")!=0)
{
om2.setVisible(false);
om3.setVisible(false);
}
om1.addActionListener(menuItemMonitor);
om2.addActionListener(menuItemMonitor);
om3.addActionListener(menuItemMonitor);
if (userid.compareToIgnoreCase("Admin")==0)
{
optionsAdminMenu.add(om2);
optionsAdminMenu.add(om3);
}
optionsMenu.add(om1);
if (userid.compareToIgnoreCase("Admin")==0)
{
optionsMenu.addSeparator();
optionsMenu.add(optionsAdminMenu);
}
/**** Help Menu ****/
helpMenu = new JMenu("Help");
hm1 = new JMenuItem("About");
hm1.addActionListener(menuItemMonitor);
helpMenu.add(hm1);
/**** Menu set up ****/
menuBar = new JMenuBar();
menuBar.add(fileMenu);
menuBar.add(viewsMenu);
menuBar.add(optionsMenu);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
}
public Dimension getPreferredSize()
{
return new Dimension(600,400);
}
}
public static void SetUI() throws Exception
{
UIManager.LookAndFeelInfo[] looks = UIManager.getInstalledLookAndFeels();
for(int i=0;i<looks.length;i++)
{
String className = looks[i].getClassName();
if (className.indexOf(settings.look) != -1)
{
UIManager.setLookAndFeel(className);
break;
}
else
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
}
}
public void UpdateAllUI()
{
messageList.updateUI();
userList.updateUI();
messageField.updateUI();
fileMenu.updateUI();
viewsMenu.updateUI();
optionsMenu.updateUI();
optionsAdminMenu.updateUI();
helpMenu.updateUI();
fm3.updateUI();vm4.updateUI();hm1.updateUI();
vm1.updateUI();vm2.updateUI();vm3.updateUI();
om1.updateUI();om2.updateUI();om3.updateUI();
sendButton.updateUI();
sendPrivateButton.updateUI();
exitButton.updateUI();
scrollPane.updateUI();scrollUser.updateUI();
scrollPane.getVerticalScrollBar().updateUI();scrollUser.getVerticalScrollBar().updateUI();
commandPanel.updateUI();
menuBar.updateUI();
}
class MenuItemMonitor implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
if ( ((JMenuItem) e.getSource()).getText().compareTo("Exit") == 0)
{
server.broadcastRemovedUser(userid);
saveUserSetting();
System.exit(0);
}
else if ( ((JMenuItem) e.getSource()).getText().compareTo("Metal") == 0)
{
settings.look = "Metal";
SetUI();
UpdateAllUI();
}
else if ( ((JMenuItem) e.getSource()).getText().compareTo("Window") == 0)
{
settings.look = "Window";
SetUI();
UpdateAllUI();
}
else if ( ((JMenuItem) e.getSource()).getText().compareTo("Motif") == 0)
{
settings.look = "Motif";
SetUI();
UpdateAllUI();
}
else if ( ((JMenuItem) e.getSource()).getText().compareTo("Clear Chat") == 0)
{
listModel.clear();
}
else if ( ((JMenuItem) e.getSource()).getText().compareTo("History") == 0)
{
settings.history = ((JMenuItem) e.getSource()).isSelected();
}
else if ( ((JMenuItem) e.getSource()).getText().compareTo("View Log") == 0)
{
getLog();
}
else if ( ((JMenuItem) e.getSource()).getText().compareTo("Clear Log") == 0)
{
listModel.clear();
clearLog();
}
else if ( ((JMenuItem) e.getSource()).getText().compareTo("About") == 0)
{
JOptionPane.showMessageDialog(null,"A project by\nPoi WeiChao Admin : 991164s\nWilliam Liew Admin : ", "About",JOptionPane.INFORMATION_MESSAGE);
}
}catch(Exception ae){System.out.println("Error : " + ae.getMessage());}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -