Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Rui Moreira Some useful links: http://java.sun.com/docs/books/tutorial/uiswing/toc.html http://www.unix.org.ua/orelly/java-ent/jfc/ Graphical User Interfaces n Java provides a good integration with interactive web-based applications - Applets, JSP, Servlets n The Java Foundation Classes (JFC) include packages (cf. AWT & Swing J2SE) with built-in components and functionality for assembling GUIs n Both packages provide mechanisms for building GUI interfaces (e.g., windows, buttons, text fields, etc.) Rui Moreira 2 1
AWT vs Swing n No big architecture differences between AWT and Swing since both define an euivalent class hierarchy, but using different packages, e.g.: java.awt.frame javax.swing.jframe java.awt.panel javax.swing.jpanel java.awt.dialog javax.swing.jdialog java.awt.button javax.swing.jbutton java.awt.textfield javax.swing.jtextfield java.awt.label javax.swing.jlabel java.awt.checkbox javax.swing.jcheckbox java.awt.combobox javax.swing.jcombobox java.awt.list java.swing.jlist n Major difference is related with rendering (how components are drawn/displayed on screen) n We cannot use/combine components from both packages in the same GUI (container) although they share Layout Managers Rui Moreira 3 AWT n The first Java package (java.awt) for building GUI components was AWT (Abstract Window Toolkit) - JDK 1.0 & JDK 1.1. n Graphical components look different in different Operating System (OS) n Defines/uses heavy-weight components each owning its own viewport which sends output info (via OS) to the screen n Each component has less code (than counterpart Swing) because it uses a peer component (Native Screen Source) provided by the OS which renders the component to screen Rui Moreira 4 2
Swing n Since J2SE (JDK1.2) Java includes a new package (javax.swing) which is a pure Java release n Graphical components look the same in different Operating System (OS) n Defines/uses light-weight components each redirects drawing to the component it build on n Each component has more code (than counterpart AWT) because it provides a richer and OS-independent functionality natively implemented in the component n All components use the same OS peer component for rendering Rui Moreira 5 Major elements n GUI Components (e.g., Button, Label, TextField) Graphical elements responsible for the interaction and that may live inside containers n Containers (e.g., Frame, Panel, Dialog) Components that group/assemble several graphical elements or even other containers n Layout Managers (e.g., FlowLayout, BorderLayout, GridLayout) Elements responsible for managing/structuring the way components are added/organized inside a container n Events (e.g., ActionEvent, MouseEvent, WindowEvent) Objects that describe an action performed by the user on interface elements n Listeners/Handlers (e.g., ActionListener, MouseListener) Elements responsible for detecting/receiving interaction events and select/execute associated action code Rui Moreira 6 3
GUI Components n There are several graphical elements/components that may be instantiated and added to a container to be displayed on screen: // Using AWT Button b = new Button( Ok ); Label l = new Label( Press ok ); TextBox t = new TextBox(); // Using Swing JButton jb = new JButton( Ok ); JLabel jl = new JLabel( Press ok ); JTextBox jt = new JTextBox(20); Rui Moreira 7 Containers n There are several types of containers which are used to group together several GUI components n Each container may include several GUI components and may also include other inner containers (to mix together different layouts) // Using AWT Frame f = new Frame( AWT Frame Example ); Panel p = new Panel(); // Using Swing JFrame jf = new JFrame( Swing Frame Example ); JPanel jp = new JPanel(); Rui Moreira 8 4
AWT GUI Components hierarchy Legend: Rui Moreira 9 Swing hierarchy Legend: Rui Moreira 10 5
Add Component to Container import java.awt.container; import javax.swing.*; /** TestButton: class for testing a Button inside Frame */ public class TestButton { public static void void main(string args[]){ // CREATE JFrame (container) & JButton (component) JFrame jf = new JFrame( Frame Test button ); JButton jb = new JButton( Ok ); // GET Container reference to ADD JButton Container c = g.getcontentpane(); c.add( Center, b); // Pack and Show f.pack(); f.setvisible(true) //Deprecated: f.show(); Rui Moreira 11 Layout Managers n Layout Managers are responsible for adding/organizing GUI elements inside containers n Layout Managers control the position and size of each GUI component inside the container n Each container has a reference to its Layout Manager and whenever we add a GUI component to the container it invokes the respective Layout Manager to do it (deciding the size and position of the component to be added) n Each container has a default Layout Manager (that we may change) Rui Moreira 12 6
AWT Layout Managers n FlowLayout: positions GUI components in lines (centered) like words in a text page (default for Panel and Applet) n BorderLayout: positions GUI components on 5 different predefined areas - North, South, West, East and Center (default for Frame, Window and Dialog) n CardLayout: organizes interfaces like layers; we may only see a layer/card at a time n GridLayout: positions GUI components over a pre-defined grid/matrix; number of lines & columns are specified by developer n GridBagLayout: positions GUI components over a pre-defined grid/matrix but columns may have different sizes and GUI components may overlap several columns Rui Moreira 13 Layout Managers hierarchy NB: Swing containers (e.g., JFrame, JPanel) use these AWT Layout Managers Rui Moreira 14 7
Set JFrame Layout import java.awt.flowlayout; import javax.swing.*; public class TestButton { public static void void main(string args[]){ // CREATE JFrame (container) & JButton (component) JFrame jf = new JFrame( Frame Test button ); JButton jb = new JButton( Ok ); // GET Container reference to ADD JButton Container c = g.getcontentpane(); // SET JFrame LAYOUT (by default is BorderLayout) c.setlayout(new FlowLayout()); c.add( Center, b); // Pack and Show f.pack(); f.setvisible(true) //Deprecated: f.show(); Rui Moreira 15 Events n When users act over GUI components one/several events may be triggered n Events are described by pre-defined classes/objects which characterize the event and its source component, e.g., ActionEvent: action events on buttons/menus, e.g., action performed MouseEvent: mouse events, e.g., moved, pressed, entered, etc. WindowEvent: window events, e.g., closing, iconified, etc. ItemEvent: list box events, e.g., item state changed TextEvent: text box events, e.g., text value changed Rui Moreira 16 8
AWT Events hierarchy NB: Swing components (e.g., JFrame, JButton, JTextField) also detect/delegate these events to listeners/handlers Rui Moreira 17 Swing Events hierarchy Legend: Rui Moreira 18 9
Listeners/Handlers n Java provides/implements a Delegation Event Model: each GUI component detects its own events - triggered by specific user-interactions (e.g., press button, move mouse, etc.) to detect these events developers must register specific eventlisteners with each GUI component GUI components then delegate/forward event handling to these pre-registered methods - handlers n Event Listeners are specific Java interfaces (e.g., ActionListener, MouseListener) that group/define methods for handling particular sets of events n Event-Handlers are classes (built by developers) that implement specific Event-Listeners, i.e., provide methods/behavior that will receive the event objects and act accordingly Rui Moreira 19 AWT Listeners hierarchy Rui Moreira 20 10
Swing Listeners hierarchy Rui Moreira 21 Implement an Event-Handler import java.awt.event.*; /** ButtonHandler: class that we implement for handling events related with buttons pressed */ public class ButtonHandler implements ActionListener { // The ActionListener interface defines only // the actionperformed() method public void actionperformed(actionevent ae){ JButton jb = (JButton )ae.getsource(); String sb = ae.getactioncommand(); // sb=jb.gettext(); // Just print out the button name System.out.println( Someone pressed button +sb); Rui Moreira 22 11
Register an Event-Handler import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestButton { public static void void main(string args[]){ JFrame jf = new JFrame( Frame Test button ); JButton jb = new JButton( Ok ); // REGISTER event-handler with Button b.addactionlistener(new ButtonHandler()); // Add Button to Frame ( Center of BorderLayout) Container c = g.getcontentpane(); c.add( Center, b); f.pack(); f.setvisible(true) //Deprecated: f.show(); Rui Moreira 23 Listeners/Handlers n The Button class has a specific method - addactionlistener() - for registering an ActionListener Handler with the button n Buttons trigger/detect ActionEvents which are handled by a specific method - actionperformed() - defined in the ActionListener interface n Developers must implement specific ActionListener Handlers for dealing with the ActionEvents of each button Rui Moreira 24 12
Listeners/Handlers n Each GUI component provides specific methods for registering different types of Listeners/Handlers, e.g., addmouselistener() is provided by buttons for registering MouseListener Handlers; addwindowlistener() is provided by containers (e.g., Frame) for registering WindowListener Hanlders n Each event category is detected by specific listeners which define particular sets of methods for handling those events n Methods defined by Event Listener interfaces are intuitively named according to the handled events Rui Moreira 25 Examples of Events Categories Event Listener Methods ActionEvent ActionListener actionperformed() MouseEvent MouseMotionListener mousedragged(), mousemoved() MouseEvent MouseListener mousepressed(), mousereleased(), etc. WindowEvent WindowListener windowclosing(), windowopened(), etc. TextEvent TextListener textvaluechanged() ItemEvent ItemListener itemsatechanged() Rui Moreira 26 13
Adapters n For each Listener interface Java defines a correspondent Adapter, e.g., MouseListener interface MouseAdapter class ActionListener interface ActionAdapter class n Adapters are classes which implement Listener interfaces but with empty methods n Developers may use (via extends) Adapters to code event handlers without having to implement all the methods defined in Listener interfaces Rui Moreira 27 Delegation Model Advantages n The Delegation Model has some advantages in comparison with the hierarchical model previously used by JDK1.0: Events are no longer accidentally resolved (handled) by containers (in the hierarchical model events could propagate to upper-level containers and then unexpectedly handled by them) Developers my create several filter classes (Adapters) to classify/select event actions The delegation model is more suitable for distributing work among different event-handler classes The delegation model provides support for Java Beans Rui Moreira 28 14
Exercises n Implement the following GUIs: ColoredFrame: JFrame with 2 JButtons (blue, yellow) that change the background color of the frame; LoginFrame: JFrame with JLabels, JTextFields, JPasswordFields and JButtons to perform a login (just print out the content of the text and password fields); ChatFrame: JFrame with JTextArea, JTextField and JButton to implement the GUI of a chat room; detect/handle ActionEvent (detect send button action cut text field to text area) and KeyEvent (detect \n key pressed on the text field cut text field to text area) by implementing ActionListener and KeyListener; use reuestfocus() method to set the focus on the text field; MenuFrame: JFrame with a menu bar that has the following menus -File, Edit, Help; File menu has options - Save, Load and Quit; Selecting the Quit menu option triggers an ActionEvent that should exit the program; Calculator: GUI calculator for basic arithmetic operations (+, -, * and /); use 3 JPanels; North panel shows output JTextField; Center JPanel uses GridLayout with all number and operation JButtons; South panel shows clear JButton. Rui Moreira 29 CardLayout Example (1/5) public class CardLayoutFrame extends JFrame implements MouseListener, WindowListener, KeyListener { // Declare/Create JPanels, JLabels, JButtons and CardLayout JPanel jp1 = new JPanel(), jp2 = new JPanel(), jp3 = new JPanel(), jp4 = new JPanel(); JLabel jl1 = new JLabel( Panel 1 ), jl2 = new JLabel( Panel 2 ), jl3 = new JLabel( Panel 3 ), jl4 = new JLabel( Panel 4 ); JButton jb1 = new JButton( Go 2 ), jb1 = new JButton( Go 3 ), jb3 = new JButton( Go 4 ), jb1 = new JButton( Go 1 ); CardLayout cl = new CardLayout(); Container c = null; // Container will be set latter // To be continue... Rui Moreira 30 15
//... Continue (2/5) public class CardLayoutFrame extends JFrame implements MouseListener, WindowListener { // Implement Constructor public CardLayoutFrame (String frametitle){ super(frametitle); // Call Constructor of JFrame c = this.getcontentpane(); // Get JFrame Container c.setlayout(this.cl); // Set layout manager of JFrame Container // Add each JPanel to a Named-Card of the JFrame container c.add(this.jp1, First ); // 1st JPanel added to card named First c.add(this.jp1, Second ); // 2nd JPanel added to card named Second... // Add each JLabel and JButton to the respective JPanel this.jp1.add(this.jl1); this.jp1.add(this.jb1);... // Set Listener/Handler (himself) for each JButton this.jb1.addactionlistener(this);... this.cl.show(c, First ); // Show First Card of JFrame Container this.setsize(200, 200); // Set JFrame size this.setvisible(true); // Set JFrame visible // To be continue... Rui Moreira 31 //... Continue (3/5) public class CardLayoutFrame extends JFrame implements MouseListener, WindowListener { //... // Implementing MouseListener public void actionperformed(actionevent ae){ String str = ae.getactioncommand(); // Check/Select which Card to Show if (str.eualsignorecase( Go 2 )){ this.cl.show(this.c, Second ); else if (str.eualsignorecase( Go 3 )){ this.cl.show(this.c, Third );... else if (str.eualsignorecase( Go 1 )){ this.cl.show(this.c, First ); // To be continue... Rui Moreira 32 16
//... Continue (4/5) public class CardLayoutFrame extends JFrame implements MouseListener, WindowListener { // Implementing WindowListener public void windowactivated(windowevent e) { public void windowclosed(windowevent e) { // Implement only the Close button of JFrame - Exit public void windowclosing(windowevent e) { this.c.dispose(); // Dispose JFrame System.exit(0); // Exit Application public void windowdeactivated(windowevent e) { public void windowdeiconified(windowevent e) { public void windowiconified(windowevent e) { public void windowopened(windowevent e) { // To be continue... Rui Moreira 33 //... Continue (5/5) public class CardLayoutFrame extends JFrame implements MouseListener, WindowListener { //... // Run Application public static void main(string args[]){ CardLayoutFrame cf = new CardLayoutFrame( Test CardLayout ); cf.setsize(200, 200); cf.setvisible(true); // The End Rui Moreira 34 17