PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.

Slides:



Advertisements
Similar presentations
CS18000: Problem Solving and Object-Oriented Programming.
Advertisements

Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
GUI’s and eventhandlers in java Martin Jagersand.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Graphical User Interfaces
More on Creating GUIs in Java using Swing David Meredith Aalborg University.
Java Programming Chapter 10 Graphical User Interfaces.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Concurrent Programming and Threads Threads Blocking a User Interface.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Next week: »No Lectures »No Labs »Recitation.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Lec.10 (Chapter 8 & 9) GUI Jiang (Jen) ZHENG June 27 th, 2005.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
UID – Event Handling and Listeners Boriana Koleva
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Object-Oriented Programming (Java), Unit 28 Kirk Scott 1.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Review_6 AWT, Swing, ActionListener, and Graphics.
Chapter 11 - A GUI Interacting With a Problem Domain Class1 Chapter 11 A GUI Interacting With a Problem Domain Class 11.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Creating a GUI Class An example of class design using inheritance and interfaces.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
TCU CoSc Programming with Java The JFrame Class.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Modular Event Handling
GUIs and Events Rick Mercer.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Lecture 27 Creating Custom GUIs
A Quick Java Swing Tutorial
Ellen Walker Hiram College
PC02 Consolidation %WITTY_QUOTE%. PC02 Consolidation %WITTY_QUOTE%
A Quick Java Swing Tutorial
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
Tonga Institute of Higher Education
Graphical User Interface
Presentation transcript:

PC02 Term 1 Project Basic Messenger

Basic Messenger You will create a program that allows you to exchange messages on your computer

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

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

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:

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

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…

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); } });

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:");

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

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

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

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

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

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();

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

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

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

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

Now you should have a working chat: Sending messages Exercise (3) Now you should have a working chat:

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

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

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”

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); } });

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)

Handling disconnections You should now see a message every time someone joins or leaves the chat

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

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));

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

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

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!

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:

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