Package edu.ups.gamedev.net.chat

Source Code of edu.ups.gamedev.net.chat.ChatClient

package edu.ups.gamedev.net.chat;

import com.captiveimagination.jgn.JGN;
import com.captiveimagination.jgn.clientserver.JGNClient;
import com.captiveimagination.jgn.event.DebugListener;
import com.captiveimagination.jgn.event.DynamicMessageAdapter;

import edu.ups.gamedev.net.Client;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
*
* @author Andrew Blaine
*/
public class ChatClient extends DynamicMessageAdapter implements ActionListener {
 
  private JGNClient JGNclient;
  private String nickname;
  private JTextPane textPane;
  private JTextField textField;
 
  public ChatClient(Client client) throws Exception {
    JGNclient = client.getJGNClient();
    JGN.register(PlayerChatMessage.class);

    JGNclient.addMessageListener(this);
    JGNclient.addMessageListener(new DebugListener("ChatClient>"));
   
    nickname = JOptionPane.showInputDialog("Connection established to server\n\nPlease enter the name you wish to use?");
    initGUI();
  }
 
  private void initGUI() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)// TODO fix
    frame.setTitle("Chat Client - " + nickname);
    frame.setSize(300, 300);
    Container c = frame.getContentPane();
    c.setLayout(new BorderLayout());
    textPane = new JTextPane();
    textPane.setText("");
    textPane.setEditable(false);
    c.add(BorderLayout.CENTER, textPane);
    textField = new JTextField();
    textField.addActionListener(this);
    c.add(BorderLayout.SOUTH, textField);
    frame.setVisible(true);
  }

  public void actionPerformed(ActionEvent evt) {
    String txt = textField.getText().trim();
    if (txt.length() > 0) {
      PlayerChatMessage message = new PlayerChatMessage();
      message.setPlayerName(nickname);
      message.setText(txt);

      if (txt.startsWith("/")) {
        JGNclient.sendToServer(message);
      } else {
        JGNclient.broadcast(message);
      }

      textField.setText("");
      writeMessage(JGNclient.getPlayerId(), nickname, message.getText());
    }
  }

  public void messageReceived(PlayerChatMessage message) {
    writeMessage(message.getPlayerId(), message.getPlayerName(), message.getText());
  }

  private void writeMessage(short playerId, String playerName, String text) {
    String message = "[" + playerName + ":" + playerId + "]: " + text;
    if (textPane.getText().length() == 0) {
      textPane.setText(message);
    } else {
      textPane.setText(textPane.getText() + "\r\n" + message);
    }
    System.out.println(message);
  }
}
TOP

Related Classes of edu.ups.gamedev.net.chat.ChatClient

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.