Amigo continuo com dúvida.
Ja ta quase tudo pronto, só falta esse detalhe de pegar da área de texto e enviar para o servidor, eu fiz usando o console e da blz.
No método run() e conectar() que está o pipino.
Já que uso evento do teclado, quando apertar <ENTER> e enviada a mensagem, ta dando erro.
Olha o código logo abaixo.
package SODChat;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
* Builder, which is free for non-commercial use. If Jigloo is being used
* commercially (ie, by a corporation, company or business for any purpose
* whatever) then you should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details. Use of Jigloo implies
* acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
* PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
* ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class Cliente extends Thread implements ActionListener, KeyListener,
ChangeListener, Runnable {
private JTabbedPane tab;
private JPanel conectar;
private JSeparator cSepaI;
private JLabel lPorta;
private JButton lBConect;
private JLabel lMeuNome;
private JSeparator lSeparIII;
private JSeparator cSeparIV;
private JLabel cImagemRede;
private JTextField cTextNomePC;
private JTextField cMeuIP;
private JLabel limagem;
private JTextField lTextIP;
private JTextField lTextPorta;
private JTextField lTextNome;
private JLabel lMeuIP;
private JLabel lOutrasInfo;
private JSeparator lSeparII;
private JLabel lIP;
private JLabel lNome;
private JLabel ltitulo;
private JPanel chat;
private JFrame frame;
private Socket conexao;
private static boolean done = false;
String meuNome = "";
public Cliente(){
}
public Cliente(Socket s) throws IOException {
conexao = s;
}
private void GUI() {
try {
frame = new JFrame("CLIENTE (SODCHAT) v1.0");
frame.setResizable(false);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
{
tab = new JTabbedPane();
frame.getContentPane().add(tab, BorderLayout.CENTER);
tab.setBounds(0, 0, 440, 450);
{
chat = new JPanel();
{
conectar = new JPanel();
tab.addTab("LOGIN", null, conectar, null);
conectar.setLayout(null);
conectar.setPreferredSize(new java.awt.Dimension(434,
378));
conectar.setBorder(BorderFactory
.createBevelBorder(BevelBorder.LOWERED));
{
ltitulo = new JLabel();
conectar.add(ltitulo);
ltitulo.setText("CHAT v1.0");
ltitulo.setBounds(133, 0, 175, 42);
ltitulo.setFont(new java.awt.Font("Tahoma", 1, 20));
ltitulo
.setForeground(new java.awt.Color(128, 0, 0));
ltitulo
.setHorizontalAlignment(SwingConstants.CENTER);
}
{
cSepaI = new JSeparator();
conectar.add(cSepaI);
cSepaI.setBounds(0, 42, 434, 7);
cSepaI.setBorder(new LineBorder(new java.awt.Color(
0, 0, 0), 1, false));
}
{
lNome = new JLabel();
conectar.add(lNome);
lNome.setText("NOME ");
lNome.setBounds(84, 56, 63, 28);
lNome.setHorizontalAlignment(SwingConstants.CENTER);
lNome.setFont(new java.awt.Font("Tahoma", 1, 12));
}
{
lIP = new JLabel();
conectar.add(lIP);
lIP.setText("IP DO SERVIDOR");
lIP.setBounds(56, 119, 112, 28);
lIP.setHorizontalAlignment(SwingConstants.CENTER);
lIP.setFont(new java.awt.Font("Tahoma", 1, 12));
}
{
lPorta = new JLabel();
conectar.add(lPorta);
lPorta.setText("PORTA");
lPorta.setBounds(77, 175, 63, 28);
lPorta.setFont(new java.awt.Font("Tahoma", 1, 12));
lPorta
.setHorizontalAlignment(SwingConstants.CENTER);
}
{
lSeparII = new JSeparator();
conectar.add(lSeparII);
lSeparII.setBounds(0, 245, 434, 7);
lSeparII.setBorder(new LineBorder(
new java.awt.Color(0, 0, 0), 1, false));
}
{
lOutrasInfo = new JLabel();
conectar.add(lOutrasInfo);
lOutrasInfo.setText("OUTRAS INFORMAÇÕES");
lOutrasInfo.setBounds(7, 259, 266, 28);
lOutrasInfo.setFont(new java.awt.Font("Tahoma", 1,
20));
lOutrasInfo.setForeground(new java.awt.Color(64, 0,
0));
lOutrasInfo
.setHorizontalAlignment(SwingConstants.CENTER);
}
{
lBConect = new JButton();
conectar.add(lBConect);
lBConect.setText("Conectar...");
lBConect.setBounds(252, 217, 175, 21);
lBConect
.setFont(new java.awt.Font("Tahoma", 1, 12));
lBConect.addActionListener(this);
}
{
lMeuIP = new JLabel();
conectar.add(lMeuIP);
lMeuIP.setText("MEU IP");
lMeuIP.setBounds(21, 312, 63, 28);
lMeuIP.setHorizontalAlignment(SwingConstants.LEFT);
lMeuIP.setFont(new java.awt.Font("Tahoma", 1, 12));
}
{
lMeuNome = new JLabel();
conectar.add(lMeuNome);
lMeuNome.setText("NOME DO PC");
lMeuNome.setBounds(21, 369, 91, 28);
lMeuNome
.setHorizontalAlignment(SwingConstants.LEFT);
lMeuNome
.setFont(new java.awt.Font("Tahoma", 1, 12));
}
{
lTextNome = new JTextField();
conectar.add(lTextNome);
lTextNome.setBounds(35, 91, 154, 21);
lTextNome
.setHorizontalAlignment(SwingConstants.CENTER);
lTextNome
.setFont(new java.awt.Font("Tahoma", 0, 12));
lTextNome
.setForeground(new java.awt.Color(0, 0, 64));
}
{
lTextPorta = new JTextField();
conectar.add(lTextPorta);
lTextPorta.setBounds(35, 210, 154, 21);
lTextPorta
.setHorizontalAlignment(SwingConstants.CENTER);
lTextPorta.setFont(new java.awt.Font("Tahoma", 0,
12));
lTextPorta.setForeground(new java.awt.Color(0, 0,
64));
lTextPorta.setText("5151");
lTextPorta.setEditable(false);
}
{
lTextIP = new JTextField();
conectar.add(lTextIP);
lTextIP.setBounds(35, 154, 154, 21);
lTextIP
.setHorizontalAlignment(SwingConstants.CENTER);
lTextIP.setFont(new java.awt.Font("Tahoma", 0, 12));
lTextIP.setForeground(new java.awt.Color(0, 0, 64));
}
{
limagem = new JLabel();
limagem.setIcon(new ImageIcon(getClass()
.getResource("messenger.jpg")));
conectar.add(limagem);
limagem.setBounds(252, 56, 175, 154);
}
{
lSeparIII = new JSeparator();
conectar.add(lSeparIII);
lSeparIII.setBounds(245, 49, 7, 196);
lSeparIII.setOrientation(SwingConstants.VERTICAL);
}
{
cMeuIP = new JTextField();
conectar.add(cMeuIP);
cMeuIP.setBounds(119, 315, 147, 21);
cMeuIP
.setHorizontalAlignment(SwingConstants.CENTER);
cMeuIP.setFont(new java.awt.Font("Tahoma", 1, 12));
cMeuIP.setForeground(new java.awt.Color(128, 0, 0));
cMeuIP.setEditable(false);
cMeuIP.setText(InetAddress.getLocalHost()
.getHostAddress());
}
{
cTextNomePC = new JTextField();
conectar.add(cTextNomePC);
cTextNomePC.setBounds(119, 371, 147, 21);
cTextNomePC
.setHorizontalAlignment(SwingConstants.CENTER);
cTextNomePC.setFont(new java.awt.Font("Tahoma", 1,
12));
cTextNomePC.setForeground(new java.awt.Color(128,
0, 0));
cTextNomePC.setEditable(false);
cTextNomePC.setText(InetAddress.getLocalHost()
.getHostName());
}
{
cImagemRede = new JLabel();
conectar.add(cImagemRede);
cImagemRede.setBounds(301, 259, 126, 154);
cImagemRede.setIcon(new ImageIcon(getClass()
.getResource("redePC.jpg")));
cImagemRede
.setHorizontalAlignment(SwingConstants.CENTER);
}
{
cSeparIV = new JSeparator();
conectar.add(cSeparIV);
cSeparIV.setBounds(294, 252, 7, 168);
cSeparIV.setOrientation(SwingConstants.VERTICAL);
}
}
}
}
tab.addTab("CLIENTE", null, panCliente(lTextIP.getText()), null);
frame.pack();
frame.setSize(449, 485);
centralizar(frame);
frame.setVisible(true);
tab.setEnabledAt(1, false);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Variáveis da interface gráfica ( CLIENTE ).
*/
private JTextArea entrada;
private JTextArea mensagens;
private JLabel LTitulo;
private JScrollPane scrollPaneI;
private JScrollPane scrollPaneII;
private JButton BcorFonte;
private JButton BcorPainel;
private JButton Blimpar;
private JSeparator separ;
private JToggleButton bTop;
public JPanel panCliente(String ip) {
chat = new JPanel();
chat.setLayout(null);
chat.setPreferredSize(new java.awt.Dimension(434, 399));
chat.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
scrollPaneI = new JScrollPane(mensagens);
chat.add(scrollPaneI);
scrollPaneI.setBounds(14, 42, 413, 273);
mensagens = new JTextArea();
mensagens.setLineWrap(true);
mensagens.setEditable(false);
scrollPaneI.setViewportView(mensagens);
LTitulo = new JLabel();
chat.add(LTitulo);
LTitulo.setBounds(14, 6, 413, 26);
LTitulo.setFont(new java.awt.Font("Verdana", 1, 18));
LTitulo.setForeground(new java.awt.Color(0, 0, 160));
LTitulo
.setBorder(BorderFactory
.createEtchedBorder(BevelBorder.LOWERED));
LTitulo.setHorizontalAlignment(SwingConstants.CENTER);
BcorPainel = new JButton();
chat.add(BcorPainel);
BcorPainel.setText("COR FUNDO");
BcorPainel.setBounds(14, 325, 133, 21);
BcorPainel.setBackground(new java.awt.Color(223, 221, 189));
BcorPainel.addActionListener(this);
BcorFonte = new JButton();
chat.add(BcorFonte);
BcorFonte.setText("FONTE");
BcorFonte.setBounds(161, 325, 77, 21);
BcorFonte.setBackground(new java.awt.Color(223, 221, 189));
BcorFonte.addActionListener(this);
Blimpar = new JButton();
chat.add(Blimpar);
Blimpar.setText("LIMPAR");
Blimpar.setBounds(329, 325, 98, 21);
Blimpar.setBackground(new java.awt.Color(214, 217, 187));
Blimpar.addActionListener(this);
bTop = new JToggleButton();
chat.add(bTop);
bTop.setText("TOPO");
bTop.setBounds(252, 325, 70, 21);
bTop.setBackground(new java.awt.Color(223, 221, 189));
bTop.addActionListener(this);
separ = new JSeparator();
chat.add(separ);
separ.setBounds(14, 350, 413, 7);
separ.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
scrollPaneII = new JScrollPane();
chat.add(scrollPaneII);
scrollPaneII.setBounds(14, 364, 413, 49);
scrollPaneII.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
entrada = new JTextArea(); // create entrada
scrollPaneII.setViewportView(entrada);
// entrada.setEditable(false);
entrada.setBackground(new java.awt.Color(255, 255, 255));
entrada.setFont(new java.awt.Font("Tahoma", 1, 14));
entrada.setLineWrap(true);
entrada.addKeyListener(this);
return chat;
}
/**
* AÇÕES, QUANDO O USUÁRIO CLICAR NOS BOTÕES.
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == lBConect) {
LTitulo.setText(lTextNome.getText().equals("") ? "CLIENTE"
: lTextNome.getText());
tab.setSelectedIndex(1);
tab.setEnabledAt(1, true);
tab.setEnabledAt(0, false);
SwingWorker worker = new SwingWorker() {
public Object construct() {
try {
conectar();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "a";
}
};
worker.start();
}
// botão TOPO
if (e.getSource() == bTop) {
if (bTop.isSelected())
frame.setAlwaysOnTop(true);
else
frame.setAlwaysOnTop(false);
}
// Botão LIMPAR
if (e.getSource() == Blimpar) {
entrada.setText("");
mensagens.setText("");
}
// Botão COR PAINEL
if (e.getSource() == BcorPainel) {
CorFonteFundo(false);
}
// Botão COR FONTE
if (e.getSource() == BcorFonte) {
CorFonteFundo(true);
}
// ALTERAÇÃO DE CORES, FONTE e PAINEL
if (e.getSource() == comboFontes) {
LTitulo.setFont(new Font((String) comboFontes.getSelectedItem(),
(int) comboEstilo.getSelectedIndex(), 18));
entrada.setFont(new Font((String) comboFontes.getSelectedItem(),
(int) comboEstilo.getSelectedIndex(),
TamFonte((String) comboTamanho.getSelectedItem())));
mensagens.setFont(new Font((String) comboFontes.getSelectedItem(),
(int) comboEstilo.getSelectedIndex(),
TamFonte((String) comboTamanho.getSelectedItem())));
}
if (e.getSource() == comboTamanho) {
LTitulo.setFont(new Font((String) comboFontes.getSelectedItem(),
(int) comboEstilo.getSelectedIndex(), 18));
entrada.setFont(new Font((String) comboFontes.getSelectedItem(),
(int) comboEstilo.getSelectedIndex(),
TamFonte((String) comboTamanho.getSelectedItem())));
mensagens.setFont(new Font((String) comboFontes.getSelectedItem(),
(int) comboEstilo.getSelectedIndex(),
TamFonte((String) comboTamanho.getSelectedItem())));
}
if (e.getSource() == comboEstilo) {
LTitulo.setFont(new Font((String) comboFontes.getSelectedItem(),
(int) comboEstilo.getSelectedIndex(), 18));
entrada.setFont(new Font((String) comboFontes.getSelectedItem(),
(int) comboEstilo.getSelectedIndex(),
TamFonte((String) comboTamanho.getSelectedItem())));
mensagens.setFont(new Font((String) comboFontes.getSelectedItem(),
(int) comboEstilo.getSelectedIndex(),
TamFonte((String) comboTamanho.getSelectedItem())));
}
}
/**
* EVENTOS DO TECLADO, na área de texto ao clicar <ENTER> a mensagem será
* enviada.
*/
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case Event.ENTER:
if (entrada.getText().length() != 0) {
try {
try {
enviaMensagem(entrada.getText());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
entrada.setText("");
pressionaBackSpace(); // retorna a 1º linha da área de
// texto.
} catch (AWTException e1) {
e1.printStackTrace();
}
}
break;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
/*
* xxxxxxxxxxxxxxxxxxxxx METODOS PARA ALTERAÇÃO DA COR, FONTE DA INTERFACE
* GRÁFICA xxxxxxxxxxxxxxxxxxxxxxxxx
*/
protected void pressionaBackSpace() throws AWTException {
Robot rbt = new Robot();
rbt.keyPress(KeyEvent.VK_BACK_SPACE);
rbt.keyRelease(KeyEvent.VK_BACK_SPACE);
}
/**
* Centraliza o FRAME na tela.
*/
protected static void centralizar(JFrame frame) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension windowSize = frame.getSize();
int x = (int) ((screenSize.getWidth() - windowSize.getWidth()) / 2);
int y = (int) ((screenSize.getHeight() - windowSize.getHeight()) / 2);
frame.setLocation(x, y);
}
/**
* Retorna o tamanho da FONTE
*
* @param ob ->
* valor da comboTamanho
* @return
*/
private int TamFonte(String ob) {
return Integer.parseInt(ob);
}
/**
* Variáveis para a alteração da cor e fonte da interface gráfica.
*/
private JColorChooser tcc;
private boolean controlTipo;
private JComboBox comboFontes;
private JComboBox comboTamanho;
private JComboBox comboEstilo;
/**
* Método responsável pela alteração de cores da fonte e painel da GUI.
*
* @param tipo -
* TRUE > altera o tipo de fonte e cor, FALSE -> altera a cor do
* painel.
*/
public void CorFonteFundo(boolean tipo) {
controlTipo = tipo;
JDialog.setDefaultLookAndFeelDecorated(true);
JDialog frameCor = new JDialog();
frameCor.setTitle("Alterar Cores ( CLIENTE )");
frameCor.setDefaultCloseOperation(frameCor.DISPOSE_ON_CLOSE);
frameCor.setResizable(false);
frameCor.setAlwaysOnTop(true);
tcc = new JColorChooser();
JPanel pan = new JPanel(new BorderLayout());
Container norte = new Container();
norte.setSize(200, 100);
norte.setLayout(new GridLayout(3, 2));
if (tipo) {
JLabel LFontes = new JLabel("FONTES");
LFontes.setFont(new Font("Arial", Font.PLAIN, 14));
JLabel LTamanho = new JLabel("TAMANHO");
LTamanho.setFont(new Font("Arial", Font.PLAIN, 14));
JLabel LEstilo = new JLabel("ESTILO");
LEstilo.setFont(new Font("Arial", Font.PLAIN, 14));
comboFontes = new JComboBox(Listarfontes().toArray());
comboFontes.addActionListener(this);
comboTamanho = new JComboBox(new String[] { "12", "14", "16", "18",
"20", "25", "30", "35", "40" });
comboTamanho.addActionListener(this);
comboEstilo = new JComboBox(new String[] { "Normal", "Negrito",
"Itálico" });
comboEstilo.addActionListener(this);
norte.add(LFontes);
norte.add(comboFontes);
norte.add(LTamanho);
norte.add(comboTamanho);
norte.add(LEstilo);
norte.add(comboEstilo);
tcc.setBorder(BorderFactory.createTitledBorder("Cores da Fonte"));
frameCor.setLocation(370, 150);
} else {
tcc.setBorder(BorderFactory.createTitledBorder("Cor do Painel"));
frameCor.setLocation(370, 200);
}
tcc.getSelectionModel().addChangeListener(this);
pan.setOpaque(true);
pan.add(norte, BorderLayout.NORTH);
pan.add(tcc, BorderLayout.CENTER);
frameCor.getContentPane().add(pan, BorderLayout.NORTH);
frameCor.pack();
frameCor.setVisible(true);
}
/**
* Lista todas as fontes que existe no PC.
*
* @return - Vector com as fontes para adicionar na comboFontes
*/
private Vector<String> Listarfontes() {
Vector<String> result = new Vector<String>();
GraphicsEnvironment env = GraphicsEnvironment
.getLocalGraphicsEnvironment();
Font[] fonts = env.getAllFonts();
for (int i = 1; i < fonts.length; i++)
result.add(fonts[i].getFontName());
return result;
}
/**
* EVENTO PARA ALTERAR AS CORES DOS COMPONENTES.
*/
public void stateChanged(ChangeEvent e) {
Color newColor = tcc.getColor();
if (controlTipo) {
entrada.setForeground(newColor);
mensagens.setForeground(newColor);
LTitulo.setForeground(newColor);
} else {
chat.setBackground(newColor);
}
}
private PrintStream saida;
public void conectar() throws ClassNotFoundException {
try {
Socket conexao = new Socket("127.0.0.1", 5151);
saida = new PrintStream(conexao.getOutputStream());
BufferedReader teclado = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("Entre com o seu nome ou Enter para Sair: ");
String meuNome = lTextNome.getText();
saida.println(meuNome);
Thread t = new Cliente(conexao); // cria a thread do cliente
t.start();
String linha;
while (true) {
System.out.print("> ");
linha = teclado.readLine();
saida.println(linha);
}
} catch (IOException e) {
System.out.println("IOException: " + e);
}
}
private void enviaMensagem(String message) throws IOException {
SimpleDateFormat form = new SimpleDateFormat("k:mm");
saida.println("\n" + meuNome.toUpperCase() + " ["
+ form.format(new Date()) + "] >> " + message);
saida.flush();
entradaMensagem("\n" + meuNome.toUpperCase() + " ["
+ form.format(new Date()) + "] >> " + message);
}
/**
* Esse método envia para a área de texto do CLIENTE as mensagens digitadas
* por ele.
*
* @param mensagem ->
* mensagens.
*/
private void entradaMensagem(final String mensagem) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
mensagens.append(mensagem);
}
});
}
public void run() {
try {
BufferedReader entrada = new BufferedReader(new InputStreamReader(
conexao.getInputStream()));
String linha;
while (true) {
// linha = entrada.readLine();
// if (linha == null) {
// System.out.println("Chat encerrado!");
// break;
// }
}
} catch (IOException e) {
System.out.println("IOException: " + e);
}
// done = true; // muda o estado da variavel para poder sair do loop
}
public static void main(String[] args) throws IOException {
new Cliente().GUI();
}
}