2 AWT Java AWT Windows, Text, & Graphics The Abstract Windows Toolkit (AWT) contains numerous classes and methods that allow you to create and manage applet windows and standard windows that run in a GUI environment, such as Windows The AWT classes are contained in the java.awt package. 3 4 Window Fundamentals AWT class Hierarchy The AWT defines windows based on a class hierarchy that adds functionality at each level. The two most common windows are those derived from Panel used by applets and Frame that creates standard windows. 5 6 AWT class Hierarchy Component is an abstract class that encapsulates all all of the user interface elements that are displayed on the screen and that interact with the user. The container class is an abstract subclass of Component. The class is responsible for laying out any components it contains through using various layout managers. AWT class Hierarchy The Panel class is a concrete subclass of Container. When screen output is directed to an applet, it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title bar, menu bar, or border.
7 8 AWT class Hierarchy Frame encapsulates what is commonly thought of as a window. It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. When a Frame window is created from within an applet window, warning message will produced. When a Frame window is created by a program, a normal window is created. Frame Windows Frame supports two constructors: Frame() & Frame(String title) You cannot specify the dimensions of the window. Instead, you must set the size after the window has been created by using the following two methods: void resize(int newwidth, int newheight) void resize(dimension newsize) 9 10 Frame Windows Once a Frame window is created, it will not be visible until you call show(). To hide a window, call hide(). To set new title, use settitle(string newtitle). import java.awt.*; public class BoringFrame1 { Using Class Frame Create a new JFrame public static void main(string[] args) { Frame test = new Frame("A Boring Frame"); Set its dimensions test.setsize(300,200); Set its position test.setlocation(100,200); test.setbackground(color.white); test.show(); Set its background colour Make it visible on the screen 11 12 import java.awt.*; public class BoringFrame2 extends Frame { public BoringFrame2() { super( Ishbel"); this.setsize(400,100); this.setlocation(100,200); this.setbackground(color.cyan); this.setvisible(true); public static void main(string[] args) { BoringFrame2 test = new BoringFrame2(); Another Frame Eventi Evento: qualcosa che l utente fa sulla interfaccia grafica Cliccare su un pulsante, scrivere in un campo. Ogni evento coinvolge tre oggetti La sorgente, ossia l oggetto che ha causato l evento (es. il pulsante cliccato) L evento, anch esso rappresentato come un oggetto (es. ActionEvent, clic di un pulsante) Il listener, ossia l oggetto che deve rispondere all evento
13 14 Oggetto listener Per gestire gli eventi è necessario implementare un listener Esempio: public class MyApplication implements ActionListener { Gestire gli eventi Il listener deve trattare il messaggio actionperformed public void actionperformed(actionevent ae) La sorgente (controllo gui) deve sapere quale oggetto gestirà gli eventi da essa prodotti (listener) calcbutton.addactionlistener(this); Metodo actionperformed public void actionperformed(actionevent event) { String name = namefield.gettext(); int rate = Integer.parseInt(rateField.getText()); Employee e = new Employee(name, rate); int hours = Integer.parseInt(hoursField.getText()); int pay = e.calcpay(hours); String result = e.getname().concat(" earned $"). concat(integer.tostring(pay)); resultlabel.settext(result); dolayout(); 15 import java.awt.*; import java.awt.event.windowevent; import java.awt.event.windowlistener; public class BoringFrame3 implements WindowListener { private Frame test; Evento WindowClosing public BoringFrame3() { test = new Frame("Closeable Frame"); test.setsize(300,200); test.setlocation(100,200); test.setbackground(color.white); test.show(); test.addwindowlistener(this); public static void main(string[] args) { BoringFrame3 app = new BoringFrame3(); public void windowclosing(windowevent we) { test.hide(); System.exit(0); 16 18 Controls Java AWT Controls Layout Managers Menus The AWT supports the following types of control subclasses of Component: Labels Buttons Check boxes Check box groups Drop-down menus Lists Scroll bars Text editing
19 20 Controls & Events Except for labels, all other controls generate events. To handle control-generated events, your program must implements the related listener interface. ActionListener AdjustmentListener AWTEventListener ComponentListener ContainerListener FocusListener HierarchyBoundsListener HierarchyListener InputMethodListener ItemListener KeyListener MouseListener MouseMotionListener MouseWheelListener TextListener WindowFocusListener WindowListener WindowStateListener Listener Interfaces The listener interface for receiving action events. The listener interface for receiving adjustment events. The listener interface for receiving notification of events dispatched to objects that are instances of Component or MenuComponent or their subclasses. The listener interface for receiving component events. The listener interface for receiving container events. The listener interface for receiving keyboard focus events on a component. The listener interface for receiving ancestor moved and resized events. The listener interface for receiving hierarchy changed events. The listener interface for receiving input method events. The listener interface for receiving item events. The listener interface for receiving keyboard events (keystrokes). The listener interface for receiving "interesting" mouse events (press, release, click, enter, and exit) on a component. The listener interface for receiving mouse motion events on a component. The listener interface for receiving mouse wheel events on a component. The listener interface for receiving text events. The listener interface for receiving WindowEvents, including WINDOW_GAINED_FOCUS and WINDOW_LOST_FOCUS events. The listener interface for receiving window events. The listener interface for receiving window state events. 21 22 Events Controls & Events ActionEvent AdjustmentEvent AWTEventListenerPro xy ComponentEvent ContainerAdapter ContainerEvent FocusEvent HierarchyBoundsAdap ter HierarchyEvent InputEvent InputMethodEvent InvocationEvent ItemEvent KeyEvent MouseEvent MouseWheelEvent PaintEvent TextEvent WindowEvent A semantic event which indicates that a component-defined action occured. The adjustment event emitted by Adjustable objects. A class which extends the EventListenerProxy, specifically for adding an AWTEventListener for a specific event mask. A low-level event which indicates that a component moved, changed size, or changed visibility (also, the root class for the other component-level events). An abstract adapter class for receiving container events. A low-level event which indicates that a container's contents changed because a component was added or removed. A low-level event which indicates that a Component has gained or lost the input focus. An abstract adapter class for receiving ancestor moved and resized events. An event which indicates a change to the Component hierarchy to which a Component belongs. The root event class for all component-level input events. Input method events contain information about text that is beingcomposed using an input method. An event which executes the run() method on a Runnablewhen dispatched by the AWT event dispatcher thread. A semantic event which indicates that an item was selected or deselected. An event which indicates that a keystroke occurred in a component. An event which indicates that a mouse action occurred in a component. An event which indicates that the mouse wheel was rotated in a component. The component-level paint event. A semantic event which indicates that an object's text changed. A low-level event that indicates that a window has changed its status. The Event class defines several fields and constants for event handling. The two most important fields are source, which contains a reference to the object that generates the event, and id, which contains the constant that identifies the event. Other event specific information are available. 23 24 Labels Label contains a string which it displays. Label defines 3 constructors: Label() Label(String str) Label(String str, int alignment) The string in a label can be changed by settext() and abstracted by gettext(). Buttons A button contains a label and generates an event when it is pressed. A button can created by: Button() or Button(String labelstr) or Button listname[] = new Button[#ofelement] The label string can be changed by setlabel() and retrieved by getlabel().
25 26 Check Boxes Check Boxes A check box is associated with a label and a state of either checked or unchecked. Check boxes are objects of the Checkbox class and can be created by: Checkbox() Checkbox(String labelstr) Checkbox(String labelstr, CheckboxGroup groupname, boolean on) Use getstate() to retrieve the current state of a check box and setstate() to set its state. Use getlabel() to retrieve the current label and setlabel() to set the label. 27 28 Check Box Group The CheckboxGroup contains a set of mutually exclusive check boxes which are often called ratio buttons. CheckboxGroup() Checkbox(labelName, groupname, boolean on) The getcurrent() method returns the check box being checked and the setcurrent() method sets a check box. Choice The Choice class creates a pop-up list of items. Each item is a string that appears as a left-justified label in the order it is added. Choice only defines the default constructor, which creates an empty line. To add an item, use additem(): additem(string name) 29 30 Choice Choice To retrieve the item being currently selected, use String getselecteditem() or int getselectindex(). To obtain the number of items in the list, use int countitems(). To set a selected item, use void select(int index) or void select(string name) To retrieve the name of an item at an index, use String getitem(int index)
31 32 List List The List class provides a compact, multiple-choice, scrolling selection list. List provides two constructors: List() List(int numrows, boolean multipleselect) To add a selection, use additem(). List selections are to be double-clicked. For lists with only one selection, current item selected can be retrieved by using String getselecteditem() or int getselectedindex() For lists with multiple selections, use String[] getselecteditems() or int[] getselectedindexes() 33 34 TextField The TextField class implements a single-line text-entry area that allowss the user to enter strings, edit the string using the arrow keys, cut and paste keys, and mouse selections TextField has four constructors: TextField() TextField(int numchars) TextField(String str) TextField(String str, int numchars) TextField Use gettext() to get current string store in the text field; use settext() to set the the text. To retrieve a portion of the text, use void select(int startindex, int endindex) To control the modifiability of the text field, use seteditable(). 35 36 Containers A Container is a GUI elements that hold other components (containers and controls) Each Container object has a layout manager associated with it. Layout Manager A layout manager is an object responsible of GUI components disposition A layout manager is an instance of any class that implements the LayoutManager interface. The layout manager is set by the setlayout() method. If no call is made to setlayout() is made, the default layout manager is used.
37 38 Layout Manager Whenever a container is resized, the layout manager is used to position each of the components within it. Each layout manager keeps track of a list of components that are stored by their names. The layout manager automatically rearranges the layout of its components. Layout Manager FlowLayout BorderLayout GridLayout CardLayout GridBagLayout 39 40 FlowLayout BorderLayout 41 42 GridLayout CardLayout colonne righe
43 44 GridBagLayout Riferimenti La documentazione java Packages: java.awt java.awt.event