KeyListener não funciona[resolvido]

6 respostas
FernandoKozlov

Galera, eu tô fazendo um chat e queria que quando a pessoa apertasse o “Enter” uma mensagem seja enviada ao servidor… :-o

public class ChatCliente extends JFrame{

	
	JTextField textoParaEnviar;
	Socket socket;
	PrintWriter escritor;
	String nome;
	JTextArea textoRecebido;
	Scanner leitor;
	JScrollPane scroll;
	
		
	private class EscutaServidor implements Runnable{

		
		public void run() {
			try {
				String texto;
				while ((texto = leitor.nextLine()) != null) {
					textoRecebido.append(texto + "\n");
					scroll.getVerticalScrollBar().setValue(textoRecebido.getHeight());
				}
			} catch (Exception e) {}
			
		}

		
		
	}
	
		
	public ChatCliente(String nome) {
		super("Protótipo - Chat : " + nome);
		this.nome = nome;
		
		Container envio = new JPanel();
		envio.setFocusable(true);
		envio.addKeyListener(new KeyListener() {
			
			@Override
			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					enviarTextoParaServidor();
				}
				
			}
			
			@Override
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}
		});
		
		envio.setLayout(new BorderLayout());
		
		Font fonte = new Font("Serif", Font.PLAIN, 26);
		textoParaEnviar = new JTextField();
		textoParaEnviar.setFont(fonte);
		JButton botao = new JButton("Enviar");
		//botao.setFocusable(true);
		//botao.addKeyListener(new EventoTecladoEnviar()); // já tentei usar o evento no botao com uma classe privada
		botao.setFont(fonte);
		botao.addActionListener(new EnviarListener());
		
		
		envio.add(BorderLayout.CENTER, textoParaEnviar);
		envio.add(BorderLayout.EAST, botao);
		
		//textarea 
		textoRecebido = new JTextArea();
		textoRecebido.setFont(fonte);
		textoRecebido.setEditable(false);
		textoRecebido.setLineWrap(true);
		scroll = new JScrollPane(textoRecebido);
		scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		
		
		getContentPane().add(BorderLayout.CENTER, scroll);
		getContentPane().add(BorderLayout.SOUTH, envio);
		
		configurarRede();
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(500, 500);
		setVisible(true);
		
		textoParaEnviar.grabFocus();
		
	}

	private class EnviarListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			enviarTextoParaServidor();
			
		}
		
	}
	
	public void enviarTextoParaServidor() {
		escritor.println(nome + " : " + textoParaEnviar.getText());
		escritor.flush();
		textoParaEnviar.setText("");
		textoParaEnviar.requestFocus();
	}
	
	
	
	private void configurarRede() {
		try{
			socket = new Socket("127.0.0.1", 5000);
			escritor = new PrintWriter(socket.getOutputStream());
			leitor = new Scanner(socket.getInputStream());
			new Thread(new EscutaServidor()).start();
			escritor.println(this.nome + " entrou na sala");
			escritor.flush();
		}catch(Exception e){
			
		}
	}
	
	public static void main(String[] args) {
		String nome = JOptionPane.showInputDialog("Qual seu nome?");
		new ChatCliente(nome);
		

	}

}

Já tentei muita coisa: usar o KeyListener no JFrame, JPanel, JButton bla bla… pesquisei aqui no GUJ… O programa funciona mas não consigo implmeentar essa função do enter nem… ou melhor não consigo manipular ação de teclado com nenhuma tecla… :twisted:

6 Respostas

gaulix

cara, coloca um breakpoint na linha 48 e ve se pelo menos o teu programa chega lá, se não chegar me fala

gaulix
textoParaEnviar.addKeyListener(new KeyListener() {  
              
            @Override  
            public void keyTyped(KeyEvent e) {  
                // TODO Auto-generated method stub  
                  
            }  
              
            @Override  
            public void keyReleased(KeyEvent e) {  
                
                  
            }  
              
            @Override  
            public void keyPressed(KeyEvent e) {  
                 if (e.getKeyCode() == KeyEvent.VK_ENTER) {  
                    enviarTextoParaServidor();  
                }  
                  
            }  
        });

ja tento isso?
voce tem que colocar o evento no textarea

FernandoKozlov
gaulix:
textoParaEnviar.addKeyListener(new KeyListener() {  
              
            @Override  
            public void keyTyped(KeyEvent e) {  
                // TODO Auto-generated method stub  
                  
            }  
              
            @Override  
            public void keyReleased(KeyEvent e) {  
                
                  
            }  
              
            @Override  
            public void keyPressed(KeyEvent e) {  
                 if (e.getKeyCode() == KeyEvent.VK_ENTER) {  
                    enviarTextoParaServidor();  
                }  
                  
            }  
        });

ja tento isso?
voce tem que colocar o evento no textarea

Cara muito obrigado....
Passei o evento no JTextField e deu certo... Como ficou o código:

public class ChatCliente extends JFrame{

	
	JTextField textoParaEnviar;
	Socket socket;
	PrintWriter escritor;
	String nome;
	JTextArea textoRecebido;
	Scanner leitor;
	JScrollPane scroll;
	JButton botao;
	
		
	private class EscutaServidor implements Runnable{

		
		public void run() {
			try {
				String texto;
				while ((texto = leitor.nextLine()) != null) {
					textoRecebido.append(texto + "\n");
					scroll.getVerticalScrollBar().setValue(textoRecebido.getHeight());
				}
			} catch (Exception e) {}
			
		}

	}
	
		
	public ChatCliente(String nome) {
		super("Protótipo - Chat : " + nome);
		this.nome = nome;
		
		Container envio = new JPanel();
		envio.setLayout(new BorderLayout());
		
		Font fonte = new Font("Serif", Font.PLAIN, 26);
		textoParaEnviar = new JTextField();
		textoParaEnviar.addKeyListener(new KeyListener() {
			
			@Override
			public void keyTyped(KeyEvent e) { }
			
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					botao.doClick();
			}
			
			@Override
			public void keyPressed(KeyEvent e) { }
		});
		textoParaEnviar.setFont(fonte);
		botao = new JButton("Enviar");
		botao.setFont(fonte);
		botao.addActionListener(new EnviarListener());
		
		
		envio.add(BorderLayout.CENTER, textoParaEnviar);
		envio.add(BorderLayout.EAST, botao);
		
		//textarea 
		textoRecebido = new JTextArea();
		textoRecebido.setFont(fonte);
		textoRecebido.setEditable(false);
		textoRecebido.setLineWrap(true);
		scroll = new JScrollPane(textoRecebido);
		scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		
		
		getContentPane().add(BorderLayout.CENTER, scroll);
		getContentPane().add(BorderLayout.SOUTH, envio);
		
		configurarRede();
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(500, 500);
		setVisible(true);
		
		textoParaEnviar.grabFocus();
		
	}

	private class EnviarListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			enviarTextoParaServidor();
			
		}
		
	}
	
	public void enviarTextoParaServidor() {
		escritor.println(nome + " : " + textoParaEnviar.getText());
		escritor.flush();
		textoParaEnviar.setText("");
		textoParaEnviar.requestFocus();
	}
	
	
	
	private void configurarRede() {
		try{
			socket = new Socket("127.0.0.1", 5000);
			escritor = new PrintWriter(socket.getOutputStream());
			leitor = new Scanner(socket.getInputStream());
			new Thread(new EscutaServidor()).start();
			escritor.println(this.nome + " entrou na sala");
			escritor.flush();
		}catch(Exception e){
			
		}
	}
	
	public static void main(String[] args) {
		String nome = JOptionPane.showInputDialog("Qual seu nome?");
		new ChatCliente(nome);
		

	}

}

Cara mas vc sabe o pq deu certo só assim? Deveria configurar o evento no JFrame ou JPanel e dar certo também, não? Sou leigo ainda :D

gaulix

Creio que não funcionou porque o keylistner pega o evento do componente que está com foco…

Se eu estiver errado me corrijam pfv.

FernandoKozlov

gaulix:
Creio que não funcionou porque o keylistner pega o evento do componente que está com foco…

Se eu estiver errado me corrijam pfv.

Eh… imagino que seja isso tbm… Mas eu tava dando foco no Frame usando o método setFocusable()…

FernandoKozlov

Consegui do outro jeito usando o método grabFocus… mas nem faz sentido usar assim. É melhor usar com o foco no componente JTextField!

Criado 30 de setembro de 2012
Ultima resposta 30 de set. de 2012
Respostas 6
Participantes 2