Download presentation
Presentation is loading. Please wait.
Published byΘαΐς Ἀναίτις Βούλγαρης Modified over 6 years ago
2
PC02 Term 1 Project Basic Messenger
3
Basic Messenger You will create a program that allows you to exchange messages on your computer
4
We will start by making the main menu of your program
Introduction We will start by making the main menu of your program It will be a small window which will only contain two buttons: one for opening a new window and one for closing the program Later we will make a separate class to handle chat windows
5
Creating the main menu (1) Exercise
Create a new Java project and make a class called MainMenu Create a constructor and define a new JFrame in it Set its default close operation, preferred size (200x100), visibility, make it unresizable and pack it Create a new JPanel called borderPanel and set its layout to “new BorderLayout(0,10)” Add it to your main frame just before you pack it
6
Creating the main menu (2) Exercise
Before pack(), declare and instantiate two JButtons: btnNew and btnExit Add both buttons to the border panel you made earlier using add() method Use BorderLayout.CENTER and BorderLayout.SOUTH Make a class called Program and instantiate MainMenu in its main method Overall, you should have something like this:
7
At the moment, our JButtons don’t do anything
Event Listeners (1) At the moment, our JButtons don’t do anything We need to add Event Listeners to them Event listeners wait for a specific event to happen and then respond to it In our case, we are waiting for the button to be clicked
8
We would need to make a new class for every button we have However…
Event Listeners (2) Event listeners implement the ActionListener interface and override one of its functions: actionPerformed An instance of this can be passed to addActionListener to attach it to a GUI element We would need to make a new class for every button we have However…
9
There is shortcut for this – we can define Anonymous classes
Event Listeners (3) There is shortcut for this – we can define Anonymous classes They don’t have a name, and are typically used when creating only one instance The code inside curly braces is what gets executed when the button is pressed btnExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } });
10
Add two event listeners to both of your buttons:
Exercise Add two event listeners to both of your buttons: One should call System.exit(0) The second one should ask you for a username and save it in a variable: Once you’re done, test your program String username = JOptionPane.showInputDialog("Please enter your username:");
11
Making a Chat Handler class
Now, we will move on to creating our client windows All windows have to be independent – we will have to run them in separate threads Every client will need to have a unique username and a list of messages We will also need a static list of chat handlers to access over clients
12
Making a Chat Handler class
Exercise (1) Create a new class called ChatHandler and make it implement Runnable interface It should have the following fields: A private string called username A private static list of chat handlers called handlers A private list of strings called messages It should also have a constructor It should accept a string and assign it to this handler’s username And add “this” to the list of handlers
13
Now it’s time to design the chat window
Adding GUI elements Now it’s time to design the chat window For now, it only needs thee elements: A text field for the message A text pane for the chat A submit button We will have to group the text field and the button in one JPanel
14
Add two private attributes to ChatHandler:
Adding GUI elements Exercise (1) Add two private attributes to ChatHandler: private JTextfield txtMessage private JTextPane txtChat Override run() and initialise a new JFrame in it Set its default close operation, preferred size (250x300), make it non-resizable, pack it and make visible
15
Make two JPanels called mainPanel and subpanel (and instantiate them!)
Adding GUI elements Exercise (2) Make two JPanels called mainPanel and subpanel (and instantiate them!) Make both of them use BorderLayout Create a button called btnSubmit Add txtMessage to the subPanel’s center Add btnSubmit to the subPanel’s east Add subPanel to mainPanel’s south
16
Make txtChat uneditable
Adding GUI elements Exercise (3) Make txtChat uneditable Make a new JScrollPane object called scroller and instantiate it like this: Add it to the center of your mainPanel Go back to MainMenu and make your button start a new thread every time it’s clicked: Test your program! JScrollPane scroller = new JScrollPane(txtChat, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); new Thread(new ChatHandler(username)).start();
17
Now we need to implement sending messages to all connected users
We will need to take the message from the text field and add it to every ChatHandler’s list of messages This will be done using a separate function
18
Make a new void function called addMessage
Sending messages Exercise (1) Make a new void function called addMessage It should accept two strings: username and text In this function, add the username and the text to messages, make sure you separate them with a colon
19
Merge all messages into one string using String.Join
Sending messages Exercise (2) Merge all messages into one string using String.Join Use “\n” as a delimiter Set text in txtChat to the merged text Go back to run() and add the following line of code: frame.getRootPane().setDefaultButton(btnSubmit); It will allow you to submit messages by just pressing enter
20
Add a new action listener to btnSubmit
Sending messages Exercise (3) Add a new action listener to btnSubmit In actionPerformed, add an if statement that checks that the text inside txtMessage is not empty Add a for loop that goes over all elements in the handlers list Call addMessage for every element using username and txtMessage.getText() as parameters Finally, set the text in txtMessage to an empty string
21
Now you should have a working chat:
Sending messages Exercise (3) Now you should have a working chat:
22
Again, this will be done in a separate function
Adding announcements We should add a system message that will be displayed every time someone joins or leaves the room Again, this will be done in a separate function It will be very similar to addMessage
23
Add a new public void function called addAnnouncement
Adding announcements Exercise (1) Add a new public void function called addAnnouncement This time, it will accept only one parameter called text Add text to the messages list Merge all messages using String.Join with “/n” as a delimiter Set text in txtChat to the merged text
24
Adding announcements Exercise (2) In ChatHadler constructor, add a for loop that goes over all handlers and calls addAnnouncement for all of them except the current one (hint: use this) The announcement message should say something like “%username% has joined the chat”
25
Handling disconnections
Handling disconnection is a little bit trickier We will need to use an anonymous WindowAdapter object, which is essentially an event listener for the window It has a method windowClosing which we will override: frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { for (ChatHandler ch : handlers) { ch.addAnnouncement(username + " has left the room"); } handlers.remove(ChatHandler.this); } });
26
Handling disconnections
Exercice In run, add a window listener to your frame Override the windowClosing method It should go over all handlers and call addAnnouncement for all of them This announcement should say “%username% has left the chat” Just before the end of windowClosing remove the current thread from the list of handlers: handlers.remove(ChatHandler.this)
27
Handling disconnections
You should now see a message every time someone joins or leaves the chat
28
It would be nice to see a list of currently active users
For that, we will need to store their usernames in a static list We will also need to add a side panel to the window
29
Add a new field to ChatHandler called users
Active users Exercise (1) Add a new field to ChatHandler called users It should be a static list of strings Call users.add(username) in your constructor Add another field called lblUsers It should be a JLabel In run, add the following lines: These will make sure the text is displayed starting from the top-left corner lblUsers.setHorizontalAlignment(JLabel.LEFT); lblUsers.setVerticalAlignment(JLabel.TOP); lblUsers.setPreferredSize(new Dimension(63, 250)); lblUsers.setBorder(new EmptyBorder(3,3,3,0));
30
We will now need to update the list of users
Active users – HTML (1) We will now need to update the list of users Every user has to be displayed on a separate line Unfortunately, “\n” doesn’t work in JLabels However, we can use basic HTML to achieve the same result
31
It is usually used with websites, but we will need to add line breaks
Active users – HTML (2) Without going to much into detail, HTML gives us better control of how the text looks like It is usually used with websites, but we will need to add line breaks All we need to do is put our text between “<html>” and “</html>” Then, we can use <br> whenever we would like to add a new line
32
Go back to the for loop inside the constructor
Active users – HTML Exercise Go back to the for loop inside the constructor Set lblUsers text to "<html>" +String.join("<br>", users) + "</html>“ Do the same in your for loop inside windowClosing Remove the username form the list of users just after removing your handler Test your program!
33
You should now have a side bar with a list of all active users:
Testing You should now have a side bar with a list of all active users:
34
You can make username and announcements use different colour
Extension You can make username and announcements use different colour For that, you will need to use html in your textPanel You’ll need to put your merged string of messages between “<html>” and “</html>” It will also need to use <br> instead of \n as its delimiter The text you want in red should be between “<font color = \"red\">” and “</font>” Using String.format might be a good idea
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.