Browse Source

Merge branch 'main' into 'JSrollBar'

# Conflicts:
#   src/main/java/ChatClient.java
remotes/origin/server
fdai7579 11 months ago
parent
commit
dd7eec1759
  1. 1
      .classpath
  2. 13
      pom.xml
  3. 26
      src/main/java/ChatClient.java
  4. 144
      src/main/java/ChatGUI.java
  5. 11
      src/main/java/ChatServer.java
  6. 12
      src/main/java/ClientHandler.java
  7. 5
      src/main/java/Constants.java
  8. 82
      src/main/java/CreateUser.java
  9. 162
      src/main/java/LoginGUI.java
  10. 37
      src/main/java/SignUpGUI.java
  11. 80
      src/test/java/ChatGUITest.java
  12. 10
      src/test/java/TestActionEvent.java
  13. 22
      user.json

1
.classpath

@ -36,5 +36,6 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5"/>
<classpathentry kind="output" path="target/classes"/> <classpathentry kind="output" path="target/classes"/>
</classpath> </classpath>

13
pom.xml

@ -11,6 +11,19 @@
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
<version>2.10.1</version> <version>2.10.1</version>
</dependency> </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

26
src/main/java/ChatClient.java

@ -2,13 +2,15 @@ import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.awt.event.KeyListener; import java.awt.event.KeyListener;
import java.io.IOException;
import java.io.*;
import java.net.Socket; import java.net.Socket;
public class ChatClient extends JFrame implements KeyListener { public class ChatClient extends JFrame implements KeyListener {
private String address; private String address;
private int port;
private String connectionFailedMessage;
private Socket connectionToServer; private Socket connectionToServer;
private BufferedReader fromServerReader;
private PrintWriter toServerWriter;
// GUI // GUI
private JTextArea outputTextArea; private JTextArea outputTextArea;
@ -17,10 +19,9 @@ public class ChatClient extends JFrame implements KeyListener {
public ChatClient(int port) { public ChatClient(int port) {
super("Chat"); super("Chat");
this.port = port;
address = JOptionPane.showInputDialog("bitte IP-Adresse"); address = JOptionPane.showInputDialog("bitte IP-Adresse");
if (address != null) {
if (null != address) {
connectionFailedMessage = "Verbindung zum Server " + (address.isEmpty() ? "" : ("\"" + address + "\"")) + " fehlgeschlagen.";
receiveMessages(); receiveMessages();
} }
} }
@ -32,6 +33,8 @@ public class ChatClient extends JFrame implements KeyListener {
outputScrollPane = new JScrollPane(outputTextArea); outputScrollPane = new JScrollPane(outputTextArea);
outputScrollPane = new JScrollPane(outputTextArea);
inputTextField = new JTextField(); inputTextField = new JTextField();
inputTextField.setBorder(BorderFactory.createTitledBorder("Nachricht eingeben")); inputTextField.setBorder(BorderFactory.createTitledBorder("Nachricht eingeben"));
inputTextField.addKeyListener(this); inputTextField.addKeyListener(this);
@ -40,12 +43,16 @@ public class ChatClient extends JFrame implements KeyListener {
add(inputTextField, BorderLayout.SOUTH); add(inputTextField, BorderLayout.SOUTH);
setVisible(true); setVisible(true);
setSize(800, 600);
setSize(Constants.WINDOW_WIDTH, Constants.WINDOW_HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE); setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
} }
private void receiveMessages() { private void receiveMessages() {
try { try {
connectionToServer = new Socket(address, port);
connectionToServer = new Socket(address, Constants.PORT);
fromServerReader = new BufferedReader(new InputStreamReader(connectionToServer.getInputStream()));
toServerWriter = new PrintWriter(new OutputStreamWriter(connectionToServer.getOutputStream()));
initGui(); initGui();
// while (true) { // while (true) {
@ -94,7 +101,8 @@ public class ChatClient extends JFrame implements KeyListener {
if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (e.getKeyCode() == KeyEvent.VK_ENTER) {
String message = inputTextField.getText(); String message = inputTextField.getText();
if (!message.isEmpty()) { if (!message.isEmpty()) {
// Senden die Nachricht an Server, wenn der erstellt wird
toServerWriter.println(message);
toServerWriter.flush();
inputTextField.setText(""); inputTextField.setText("");
} }
} }
@ -106,6 +114,6 @@ public class ChatClient extends JFrame implements KeyListener {
} }
public static void main(String[] args) { public static void main(String[] args) {
new ChatClient(3141);
new ChatClient();
} }
} }

144
src/main/java/ChatGUI.java

@ -0,0 +1,144 @@
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ChatGUI implements ActionListener {
// Menu items for font sizes
JMenuItem small = new JMenuItem("small-font");
JMenuItem medium = new JMenuItem("medium-font");
JMenuItem large = new JMenuItem("large-font");
// Menu items for font colors
JMenuItem black = new JMenuItem("black");
JMenuItem red = new JMenuItem("red");
JMenuItem blue = new JMenuItem("blue");
JMenuItem green = new JMenuItem("green");
JMenuItem exit = new JMenuItem("Exit");
JTextField inputTextField = new JTextField();
JTextArea outputTextArea = new JTextArea();
JButton sendButton = new JButton("Senden");
JFrame gui;
public ChatGUI() {
gui = new JFrame();
// Set up the main frame
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setTitle("java-chat");
gui.setLayout(new BorderLayout());
// Set up the menu bar
JMenuBar bar = new JMenuBar();
gui.setJMenuBar(bar);
// Create menu items and menus
JMenu options = new JMenu("options");
JMenu colors = new JMenu("font-colors");
JMenu size = new JMenu("font-size");
JMenu menu = new JMenu("File");
menu.add(exit);
menu.add(options);
bar.add(menu);
options.add(colors);
options.add(size);
colors.add(black);
colors.add(red);
colors.add(blue);
colors.add(green);
size.add(small);
size.add(medium);
size.add(large);
// Register action listeners for menu items
red.addActionListener(this);
blue.addActionListener(this);
black.addActionListener(this);
green.addActionListener(this);
small.addActionListener(this);
medium.addActionListener(this);
large.addActionListener(this);
exit.addActionListener(this);
bar.add(menu);
// Set up the output text area with scrolling
JScrollPane outputScrollPane = new JScrollPane(outputTextArea);
gui.add(outputScrollPane, BorderLayout.CENTER);
// Set up the input panel with text field and send button
JPanel inputPanel = new JPanel(new BorderLayout());
inputPanel.add(inputTextField, BorderLayout.CENTER);
inputPanel.add(sendButton, BorderLayout.EAST);
gui.add(inputPanel, BorderLayout.SOUTH);
inputTextField.addActionListener(this);
sendButton.addActionListener(this);
// Set the size of the GUI to be a quarter of the screen size
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int quarterWidth = screenSize.width / 2;
int quarterHeight = screenSize.height / 2;
gui.setSize(quarterWidth, quarterHeight);
gui.setVisible(true);
}
// main methode zum Testen, müsste bei Implementation entfernt werden
public static void main(String[] args) {
new ChatGUI();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exit) {
System.exit(0);
}
if (e.getSource() == inputTextField || e.getSource() == sendButton) {
String inputText = inputTextField.getText();
outputTextArea.append(inputText + "\n");
inputTextField.setText("");
}
if (e.getSource() == red) {
outputTextArea.setForeground(Color.RED);
} else if (e.getSource() == blue) {
outputTextArea.setForeground(Color.BLUE);
} else if (e.getSource() == black) {
outputTextArea.setForeground(Color.BLACK);
} else if (e.getSource() == green) {
outputTextArea.setForeground(Color.GREEN);
}
if (e.getSource() == small) {
outputTextArea.setFont(outputTextArea.getFont().deriveFont(Font.PLAIN, 12));
}
if (e.getSource() == medium) {
outputTextArea.setFont(outputTextArea.getFont().deriveFont(Font.PLAIN, 16));
}
if (e.getSource() == large) {
outputTextArea.setFont(outputTextArea.getFont().deriveFont(Font.PLAIN, 20));
}
}
}

11
src/main/java/ChatServer.java

@ -39,10 +39,10 @@ public class ChatServer {
} }
// Methode, um eine Nachricht an alle verbundenen Clients zu senden // Methode, um eine Nachricht an alle verbundenen Clients zu senden
public void broadcastMessage(String message) { public void broadcastMessage(String message) {
System.out.println(message);
if (message != null) {
for (ClientHandler client : clients) {
client.sendMessage(message); // Nachricht an jeden Client senden
System.out.println(message);
if (message != null) {
for (ClientHandler client : clients) {
client.sendMessage(message);
} }
} }
@ -56,5 +56,8 @@ public class ChatServer {
public void removeClient(ClientHandler client) { public void removeClient(ClientHandler client) {
clients.remove(client); clients.remove(client);
} }
public List<ClientHandler> getClients() {
return clients;
}
} }

12
src/main/java/ClientHandler.java

@ -1,18 +1,21 @@
import java.io.*; import java.io.*;
import java.net.Socket; import java.net.Socket;
import javax.swing.JOptionPane;
public class ClientHandler implements Runnable { public class ClientHandler implements Runnable {
private ChatServer chatServer; private ChatServer chatServer;
private Socket connectionToClient; private Socket connectionToClient;
private String name; private String name;
private BufferedReader fromClientReader; private BufferedReader fromClientReader;
private PrintWriter toClientWriter; private PrintWriter toClientWriter;
private String lastMessage;
// Constructor for ClientHandler // Constructor for ClientHandler
public ClientHandler(ChatServer chatServer, Socket connectionToClient) { public ClientHandler(ChatServer chatServer, Socket connectionToClient) {
this.chatServer = chatServer; this.chatServer = chatServer;
this.connectionToClient = connectionToClient; this.connectionToClient = connectionToClient;
name = connectionToClient.getInetAddress().getHostAddress(); // Use the client's IP address as their name for simplicity
name = JOptionPane.showInputDialog("Benutzername für neuen Client vergeben");
new Thread(this).start();} // Start a new thread for this client handler new Thread(this).start();} // Start a new thread for this client handler
@ -31,6 +34,7 @@ public class ClientHandler implements Runnable {
while (message!=null) { while (message!=null) {
// Broadcast the client's message to all connected clients // Broadcast the client's message to all connected clients
chatServer.broadcastMessage(name + ": " + message); chatServer.broadcastMessage(name + ": " + message);
lastMessage = message;
message = fromClientReader.readLine(); message = fromClientReader.readLine();
} }
} }
@ -39,7 +43,7 @@ public class ClientHandler implements Runnable {
throw new RuntimeException(e); // Handle exceptions by throwing a runtime exception throw new RuntimeException(e); // Handle exceptions by throwing a runtime exception
} }
finally { finally {
//chatServer.removeClient(this);
chatServer.removeClient(this);
chatServer.broadcastMessage(name + " disconnected."); // Broadcast a message when the client is disconnected chatServer.broadcastMessage(name + " disconnected."); // Broadcast a message when the client is disconnected
// Close resources in the finally block // Close resources in the finally block
@ -62,4 +66,8 @@ public class ClientHandler implements Runnable {
toClientWriter.println(message); // Send the message to the client toClientWriter.println(message); // Send the message to the client
toClientWriter.flush(); // Flush the stream toClientWriter.flush(); // Flush the stream
} }
//Test method
public String getLastMessage() {
return lastMessage;
}
} }

5
src/main/java/Constants.java

@ -0,0 +1,5 @@
public class Constants {
public static final int WINDOW_WIDTH = 800;
public static final int WINDOW_HEIGHT = 600;
public static final int PORT = 3141;
}

82
src/main/java/CreateUser.java

@ -10,6 +10,9 @@ import java.util.List;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID; import java.util.UUID;
class CreateUser { class CreateUser {
@ -17,14 +20,19 @@ class CreateUser {
private String userName; private String userName;
private String password; private String password;
private String birthday; private String birthday;
private String firstName;
private String surname;
private boolean stayLoggedIn;
// Constructor // Constructor
public CreateUser(String id, String name, String password, String birthday) {
public CreateUser(String id, String name, String password, String birthday, String firstName, String surname) {
this.id = id; this.id = id;
this.userName = name; this.userName = name;
this.password = password;
this.password = hashPassword(password);
this.birthday = birthday; this.birthday = birthday;
this.firstName = firstName;
this.surname = surname;
} }
// Getters and Setters // Getters and Setters
@ -60,8 +68,32 @@ class CreateUser {
this.birthday = birthday; this.birthday = birthday;
} }
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String surname() {
return firstName;
}
public void surname(String firstName) {
this.firstName = firstName;
}
public boolean isStayLoggedIn() {
return stayLoggedIn;
}
public void setStayLoggedIn(boolean stayLoggedIn) {
this.stayLoggedIn = stayLoggedIn;
}
// Function to create user with validation // Function to create user with validation
public static CreateUser createUser(String id, String userName, String password, String birthday) {
public static CreateUser createUser(String id, String userName, String password, String birthday, String firstName, String surname) {
if (userName == null || userName.isEmpty()) { if (userName == null || userName.isEmpty()) {
throw new IllegalArgumentException("Username cannot be empty"); throw new IllegalArgumentException("Username cannot be empty");
} }
@ -70,7 +102,25 @@ class CreateUser {
} }
if (password.length() < 6) { if (password.length() < 6) {
throw new IllegalArgumentException("Password must be at least 6 characters long"); throw new IllegalArgumentException("Password must be at least 6 characters long");
} return new CreateUser(id, userName, password, birthday);
} return new CreateUser(id, userName, password, birthday, firstName, surname);
}
// Function to hash the password using SHA-256 algorithm
private String hashPassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(password.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
} }
// Function to save to JSON file, replace with database call later // Function to save to JSON file, replace with database call later
@ -102,11 +152,31 @@ class CreateUser {
return userList; return userList;
} }
// Function to update stayLoggedIn variable in the JSON file
public static void updateStayLoggedIn(String filename, String username, boolean stayLoggedIn) {
List<CreateUser> userList = readUserListFromJsonFile(filename);
for (CreateUser user : userList) {
if (user.getUserName().equals(username)) {
user.setStayLoggedIn(stayLoggedIn);
break;
}
}
try (FileWriter fileWriter = new FileWriter(filename)) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.toJson(userList, fileWriter);
System.out.println("StayLoggedIn updated in " + filename);
} catch (IOException e) {
System.out.println("Error occurred while updating StayLoggedIn in JSON file: " + e.getMessage());
}
}
public static void main(String[] args) { public static void main(String[] args) {
try { try {
// Example usage // Example usage
UUID randomUUID = UUID.randomUUID(); UUID randomUUID = UUID.randomUUID();
CreateUser user = createUser(randomUUID.toString(), "Another Test User", "TestPasswort123", "01.01.2000");
CreateUser user = createUser(randomUUID.toString(), "Hash Test", "123456", "01.01.2000", "Hans", "Wurst");
// Example of accessing properties // Example of accessing properties
System.out.println("UserID: " + user.getId()); System.out.println("UserID: " + user.getId());
@ -117,6 +187,8 @@ class CreateUser {
// Save user information to a JSON file // Save user information to a JSON file
user.saveToJsonFile("user.json"); user.saveToJsonFile("user.json");
updateStayLoggedIn("user.json", "Test User", true);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage()); System.out.println("Error: " + e.getMessage());
} }

162
src/main/java/LoginGUI.java

@ -0,0 +1,162 @@
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class LoginGUI extends JFrame implements ActionListener {
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton;
private JCheckBox stayLoggedInCheckbox;
private JButton signUpButton;
public LoginGUI() {
setTitle("Login");
setSize(300, 220);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
JLabel usernameLabel = new JLabel("Username:");
usernameLabel.setBounds(20, 20, 80, 25);
add(usernameLabel);
usernameField = new JTextField();
usernameField.setBounds(100, 20, 160, 25);
add(usernameField);
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(20, 50, 80, 25);
add(passwordLabel);
passwordField = new JPasswordField();
passwordField.setBounds(100, 50, 160, 25);
add(passwordField);
stayLoggedInCheckbox = new JCheckBox("Stay Logged In");
stayLoggedInCheckbox.setBounds(20, 80, 150, 25);
add(stayLoggedInCheckbox);
loginButton = new JButton("Login");
loginButton.setBounds(100, 110, 100, 25);
loginButton.addActionListener(this);
add(loginButton);
signUpButton = new JButton("Sign Up");
signUpButton.setBounds(100, 140, 100, 25); // Adjusted position
signUpButton.addActionListener(this);
add(signUpButton);
getRootPane().setDefaultButton(loginButton);
passwordField.addKeyListener(new EnterKeyListener());
stayLoggedInCheckbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean stayLoggedIn = stayLoggedInCheckbox.isSelected();
String username = usernameField.getText();
// Set stayLoggedIn to false if the checkbox is unchecked
if (!stayLoggedInCheckbox.isSelected()) {
stayLoggedIn = false;
}
updateStayLoggedIn(username, stayLoggedIn);
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
login();
}else if (e.getSource() == signUpButton) {
SignUpGUI signUpGUI = new SignUpGUI();
signUpGUI.setVisible(true);
}
}
private void login() {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
boolean stayLoggedIn = stayLoggedInCheckbox.isSelected(); // Get checkbox state
if (authenticateUser(username, password)) {
JOptionPane.showMessageDialog(this, "Login successful!");
// Perform actions after successful login
dispose();
} else {
JOptionPane.showMessageDialog(this, "Invalid username or password", "Login Error", JOptionPane.ERROR_MESSAGE);
}
}
private void updateStayLoggedIn(String username, boolean stayLoggedIn) {
// Update stayLoggedIn in the JSON file for the user
CreateUser.updateStayLoggedIn("user.json", username, stayLoggedIn);
}
// Function to authenticate the user by comparing the entered username and password with the saved user data
private boolean authenticateUser(String username, String password) {
List<CreateUser> userList = CreateUser.readUserListFromJsonFile("user.json");
if (userList != null) {
for (CreateUser user : userList) {
if (user.getUserName().equals(username)) {
// Hash the user input password
String hashedPassword = hashPassword(password);
// Compare the hashed passwords
if (user.getPassword().equals(hashedPassword)) {
return true; // Success
}
}
}
}
return false; // Fail
}
private String hashPassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(password.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
private class EnterKeyListener implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
login();
}
}
@Override
public void keyReleased(KeyEvent e) {}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
LoginGUI loginGUI = new LoginGUI();
loginGUI.setVisible(true);
});
}
}

37
src/main/java/SignUpGUI.java

@ -5,12 +5,12 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
public class SignUpGUI extends JFrame implements ActionListener { public class SignUpGUI extends JFrame implements ActionListener {
private JTextField usernameField, passwordField, confirmPasswordField, birthdayField;
private JTextField usernameField, passwordField, confirmPasswordField, birthdayField, firstNameField, surnameField;
private JButton signUpButton; private JButton signUpButton;
public SignUpGUI() { public SignUpGUI() {
setTitle("Sign Up"); setTitle("Sign Up");
setSize(300, 250);
setSize(400, 300); // Adjusted size for accommodating more fields
setDefaultCloseOperation(EXIT_ON_CLOSE); setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null); setLayout(null);
@ -19,7 +19,7 @@ public class SignUpGUI extends JFrame implements ActionListener {
add(usernameLabel); add(usernameLabel);
usernameField = new JTextField(); usernameField = new JTextField();
usernameField.setBounds(100, 20, 160, 25);
usernameField.setBounds(140, 20, 160, 25);
add(usernameField); add(usernameField);
JLabel passwordLabel = new JLabel("Password:"); JLabel passwordLabel = new JLabel("Password:");
@ -27,7 +27,7 @@ public class SignUpGUI extends JFrame implements ActionListener {
add(passwordLabel); add(passwordLabel);
passwordField = new JPasswordField(); passwordField = new JPasswordField();
passwordField.setBounds(100, 50, 160, 25);
passwordField.setBounds(140, 50, 160, 25);
add(passwordField); add(passwordField);
JLabel confirmPasswordLabel = new JLabel("Confirm Password:"); JLabel confirmPasswordLabel = new JLabel("Confirm Password:");
@ -35,22 +35,37 @@ public class SignUpGUI extends JFrame implements ActionListener {
add(confirmPasswordLabel); add(confirmPasswordLabel);
confirmPasswordField = new JPasswordField(); confirmPasswordField = new JPasswordField();
confirmPasswordField.setBounds(140, 80, 120, 25);
confirmPasswordField.setBounds(140, 80, 160, 25);
add(confirmPasswordField); add(confirmPasswordField);
JLabel firstNameLabel = new JLabel("First Name:"); // New field for first name
firstNameLabel.setBounds(20, 110, 80, 25);
add(firstNameLabel);
firstNameField = new JTextField();
firstNameField.setBounds(140, 110, 160, 25);
add(firstNameField);
JLabel surnameLabel = new JLabel("Surname:"); // New field for surname
surnameLabel.setBounds(20, 140, 80, 25);
add(surnameLabel);
surnameField = new JTextField();
surnameField.setBounds(140, 140, 160, 25);
add(surnameField);
JLabel birthdayLabel = new JLabel("Birthday:"); JLabel birthdayLabel = new JLabel("Birthday:");
birthdayLabel.setBounds(20, 110, 80, 25);
birthdayLabel.setBounds(20, 170, 80, 25);
add(birthdayLabel); add(birthdayLabel);
birthdayField = new JTextField(); birthdayField = new JTextField();
birthdayField.setBounds(100, 110, 160, 25);
birthdayField.setBounds(140, 170, 160, 25);
add(birthdayField); add(birthdayField);
signUpButton = new JButton("Sign Up"); signUpButton = new JButton("Sign Up");
signUpButton.setBounds(100, 150, 100, 25);
signUpButton.setBounds(140, 210, 100, 25); // Adjusted position
signUpButton.addActionListener(this); signUpButton.addActionListener(this);
add(signUpButton); add(signUpButton);
} }
@Override @Override
@ -60,6 +75,8 @@ public class SignUpGUI extends JFrame implements ActionListener {
String password = passwordField.getText(); String password = passwordField.getText();
String confirmPassword = confirmPasswordField.getText(); String confirmPassword = confirmPasswordField.getText();
String birthday = birthdayField.getText(); String birthday = birthdayField.getText();
String firstName = firstNameField.getText();
String surname = surnameField.getText();
if (!password.equals(confirmPassword)) { if (!password.equals(confirmPassword)) {
JOptionPane.showMessageDialog(this, "Passwords do not match!", "Sign Up Error", JOptionPane.ERROR_MESSAGE); JOptionPane.showMessageDialog(this, "Passwords do not match!", "Sign Up Error", JOptionPane.ERROR_MESSAGE);
@ -72,7 +89,7 @@ public class SignUpGUI extends JFrame implements ActionListener {
} }
try { try {
UUID randomUUID = UUID.randomUUID(); UUID randomUUID = UUID.randomUUID();
CreateUser user = CreateUser.createUser(randomUUID.toString(), username, password, birthday);
CreateUser user = CreateUser.createUser(randomUUID.toString(), username, password, birthday, firstName, surname);
user.saveToJsonFile("user.json"); user.saveToJsonFile("user.json");
JOptionPane.showMessageDialog(this, "User signed up successfully!"); JOptionPane.showMessageDialog(this, "User signed up successfully!");
dispose(); dispose();

80
src/test/java/ChatGUITest.java

@ -0,0 +1,80 @@
import static org.junit.Assert.assertEquals;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import org.junit.Before;
import org.junit.Test;
public class ChatGUITest {
private ChatGUI chatGUI;
@Before
public void setUp() {
chatGUI = new ChatGUI();
}
@Test
public void testSetOutputTextColorRed() {
chatGUI.actionPerformed(new TestActionEvent(chatGUI.red));
assertEquals(Color.RED, chatGUI.outputTextArea.getForeground());
}
@Test
public void testSetOutputTextColorBlue() {
chatGUI.actionPerformed(new TestActionEvent(chatGUI.blue));
assertEquals(Color.BLUE, chatGUI.outputTextArea.getForeground());
}
@Test
public void testSetOutputTextColorBlack() {
chatGUI.actionPerformed(new TestActionEvent(chatGUI.black));
assertEquals(Color.BLACK, chatGUI.outputTextArea.getForeground());
}
@Test
public void testSetOutputTextColorGreen() {
chatGUI.actionPerformed(new TestActionEvent(chatGUI.green));
assertEquals(Color.GREEN, chatGUI.outputTextArea.getForeground());
}
@Test
public void testSetOutputTextFontSizeSmall() {
chatGUI.actionPerformed(new TestActionEvent(chatGUI.small));
Font expectedFont = chatGUI.outputTextArea.getFont().deriveFont(Font.PLAIN, 12);
assertEquals(expectedFont, chatGUI.outputTextArea.getFont());
}
@Test
public void testSetOutputTextFontSizeMedium() {
chatGUI.actionPerformed(new TestActionEvent(chatGUI.medium));
Font expectedFont = chatGUI.outputTextArea.getFont().deriveFont(Font.PLAIN, 16);
assertEquals(expectedFont, chatGUI.outputTextArea.getFont());
}
@Test
public void testSetOutputTextFontSizeLarge() {
chatGUI.actionPerformed(new TestActionEvent(chatGUI.large));
Font expectedFont = chatGUI.outputTextArea.getFont().deriveFont(Font.PLAIN, 20);
assertEquals(expectedFont, chatGUI.outputTextArea.getFont());
}
@Test
public void testSendButtonActionPerformed() {
chatGUI.inputTextField.setText("Testnachricht");
chatGUI.sendButton.doClick();
String expectedOutput = "Testnachricht\n";
assertEquals(expectedOutput, chatGUI.outputTextArea.getText());
}
@Test
public void testInputTextFieldActionPerformed() {
chatGUI.inputTextField.setText("Testnachricht");
chatGUI.actionPerformed(new ActionEvent(chatGUI.inputTextField, ActionEvent.ACTION_PERFORMED, ""));
String expectedOutput = "Testnachricht\n";
assertEquals(expectedOutput, chatGUI.outputTextArea.getText());
assertEquals("", chatGUI.inputTextField.getText());
}
}

10
src/test/java/TestActionEvent.java

@ -0,0 +1,10 @@
import java.awt.event.ActionEvent;
public class TestActionEvent extends ActionEvent {
private static final long serialVersionUID = 1L;
public TestActionEvent(Object source) {
super(source, ActionEvent.ACTION_PERFORMED, "Test command");
}
}

22
user.json

@ -1,14 +1,20 @@
[ [
{ {
"id": "961ca202-ecbd-4dfc-ac0b-28f367618aa1",
"userName": "asd",
"password": "123456",
"birthday": "1"
"id": "d7ae19fe-4684-4d69-a73d-4cca612962a3",
"userName": "Test",
"password": "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
"birthday": "",
"firstName": "",
"surname": "",
"stayLoggedIn": false
}, },
{ {
"id": "d563a466-753b-4a5e-8b6c-e7e4756c7397",
"userName": "asd1",
"password": "123456",
"birthday": "1"
"id": "2ec2c0c5-677c-4262-8958-fef98d11cc63",
"userName": "Test2",
"password": "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
"birthday": "",
"firstName": "",
"surname": "",
"stayLoggedIn": false
} }
] ]
Loading…
Cancel
Save