Browse Source

Merge branch 'feature/client/make-input-field-buttons-interactive' into 'main'

Create GUI window and establish connection to server

See merge request fdai7332/java-chat!2
remotes/origin/feature/client/make-input-field-buttons-interactive
fdai5595 11 months ago
parent
commit
1b4d077ed3
  1. 70
      src/main/java/ChatClient.java

70
src/main/java/ChatClient.java

@ -1,12 +1,76 @@
import javax.swing.*; 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 {
public class ChatClient extends JFrame implements KeyListener {
private String address; private String address;
public ChatClient() {
private int port;
private Socket connectionToServer;
// GUI
private JTextArea outputTextArea;
private JTextField inputTextField;
public ChatClient(int port) {
super("Chat");
this.port = port;
address = JOptionPane.showInputDialog("bitte IP-Adresse"); address = JOptionPane.showInputDialog("bitte IP-Adresse");
if (address != null) {
receiveMessages();
}
}
private void initGui() {
outputTextArea = new JTextArea();
outputTextArea.setEditable(false);
outputTextArea.setBorder(BorderFactory.createTitledBorder("Chat"));
inputTextField = new JTextField();
inputTextField.setBorder(BorderFactory.createTitledBorder("Nachricht eingeben"));
inputTextField.addKeyListener(this);
add(outputTextArea, BorderLayout.CENTER);
add(inputTextField, BorderLayout.SOUTH);
setVisible(true);
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void receiveMessages() {
try {
connectionToServer = new Socket(address, port);
initGui();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Verbindung zum Server \"" + address + "\" fehlgeschlagen.");
}
}
@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) { public static void main(String[] args) {
new ChatClient();
new ChatClient(3141);
} }
} }
Loading…
Cancel
Save