From 3800aeb4618cd70b201820622e4496dbf8c0fd46 Mon Sep 17 00:00:00 2001 From: Alena Bandarovich Date: Sat, 3 Feb 2024 21:54:23 +0100 Subject: [PATCH] Remove text from input field and later send to server after user presses enter --- src/main/java/ChatClient.java | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/src/main/java/ChatClient.java b/src/main/java/ChatClient.java index 8f0c1f0..695f622 100644 --- a/src/main/java/ChatClient.java +++ b/src/main/java/ChatClient.java @@ -1,9 +1,11 @@ import javax.swing.*; import java.awt.*; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; import java.io.IOException; import java.net.Socket; -public class ChatClient extends JFrame { +public class ChatClient extends JFrame implements KeyListener { private String address; private int port; private Socket connectionToServer; @@ -29,6 +31,7 @@ public class ChatClient extends JFrame { inputTextField = new JTextField(); inputTextField.setBorder(BorderFactory.createTitledBorder("Nachricht eingeben")); + inputTextField.addKeyListener(this); add(outputTextArea, BorderLayout.CENTER); add(inputTextField, BorderLayout.SOUTH); @@ -48,8 +51,28 @@ public class ChatClient extends JFrame { } } + @Override + public void keyTyped(KeyEvent e) { + + } + + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + String message = inputTextField.getText(); + if (!message.isEmpty()) { + // Senden die Nachricht an Server, wenn der erstellt wird + inputTextField.setText(""); + } + } + } + + @Override + public void keyReleased(KeyEvent e) { + + } + public static void main(String[] args) { new ChatClient(3141); - } -} \ No newline at end of file +}