Graphical User Interfaces Javas AWT and Swing APIs

  • Slides: 52
Download presentation
Graphical User Interfaces Java’s AWT and Swing APIs

Graphical User Interfaces Java’s AWT and Swing APIs

AWT and Swing • Java provides two sets of components for GUI programming: –

AWT and Swing • Java provides two sets of components for GUI programming: – AWT: classes in the java. awt package – Swing: classes in the javax. swing package

Abstract Window Toolkit (AWT) • The Abstract Window Toolkit is a portable GUI library.

Abstract Window Toolkit (AWT) • The Abstract Window Toolkit is a portable GUI library. • AWT provides the connection between your application and the native GUI. • AWT provides a high-level abstraction since it hides you from the underlying details of the GUI your program will be running on. • AWT components depend on native code counterparts (called peers) to handle their functionality. Thus, these components are often called heavyweight components.

Swing • Swing implements GUI components that build on AWT technology. • Swing is

Swing • Swing implements GUI components that build on AWT technology. • Swing is implemented entirely in Java. • Swing components do not depend on peers to handle their functionality. Thus, these components are often called lightweight components.

Swing Stack

Swing Stack

Some AWT and Swing Classes java. lang. Object java. awt. Component java. awt. Container

Some AWT and Swing Classes java. lang. Object java. awt. Component java. awt. Container javax. swing. JComponent java. awt. Window javax. swing. JPanel java. awt. Frame javax. swing. JFile. Chooser javax. swing. JPopup. Menu javax. swing. JFrame javax. swing. JToolbar javax. swing. JLabel

AWT: Pros and Cons • Pros – Speed: native components speed performance. – Look

AWT: Pros and Cons • Pros – Speed: native components speed performance. – Look and feel: AWT components more closely reflect the look and feel of the OS they run on. • Cons – Portability: use of native peers creates platform specific limitations. – Features: AWT supports only the lowest common denominator—e. g. no tool tips or icons.

Swing: Pros and Cons • Pros – Portability: Pure Java implementation. – Features: Not

Swing: Pros and Cons • Pros – Portability: Pure Java implementation. – Features: Not limited by native components. – Look and Feel: Pluggable look and feel. Components automatically have the look and feel of the OS their running on. • Cons – Performance: Swing components handle their own painting (instead of using APIs like Direct. X on Windows). – Look and Feel: May look slightly different than native components.

Summary of AWT vs. Swing Use Swing!

Summary of AWT vs. Swing Use Swing!

Main Steps in GUI Programming To make any graphic program work we must be

Main Steps in GUI Programming To make any graphic program work we must be able to create windows and add content to them. To make this happen we must: 1. Import the awt or swing packages. 2. 3. Set up a top-level container. Fill the container with GUI components. 4. Install listeners for GUI Components. 5. Display the container.

Hello World Example import javax. swing. *; public class Hello. World. Swing { public

Hello World Example import javax. swing. *; public class Hello. World. Swing { public static void main(String[] args) { JFrame frame = new JFrame("Hello. World. Swing"); final JLabel label = new JLabel("Hello World"); frame. get. Content. Pane(). add(label); frame. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE); frame. pack(); frame. set. Visible(true); } }

Top-level Containers • There are three top-level Swing containers – JFrame: window that has

Top-level Containers • There are three top-level Swing containers – JFrame: window that has decorations, such as a border, a title, and buttons for iconifying and closing the window – JDialog: a window that's dependent on another window – JApplet: applet's display area within a browser window

Containment Hierarchy • In the Hello World example, there was a content pane. •

Containment Hierarchy • In the Hello World example, there was a content pane. • Every top-level container indirectly contains an intermediate container known as a content pane. • As a rule, the content pane contains, directly or indirectly, all of the visible components in the window's GUI. • To add a component to a container, you use one of the various forms of the add method.

Containment Hierarchy of the Hello World Example JFrame … content pane JLabel

Containment Hierarchy of the Hello World Example JFrame … content pane JLabel

Event Example public class Swing. Application extends JFrame { private static String label. Prefix

Event Example public class Swing. Application extends JFrame { private static String label. Prefix = "Number of clicks: "; private int num. Clicks = 0; JLabel label = new JLabel(label. Prefix + "0 "); public Swing. Application(String title) { super(title); JButton button = new JButton("I'm a Swing button!"); button. add. Action. Listener(new Action. Listener() { public void action. Performed(Action. Event e) { label. set. Text(label. Prefix + ++num. Clicks); } }); JPanel panel = new JPanel(); panel. add(button); panel. add(label); get. Content. Pane(). add(panel); pack(); set. Visible(true); } public static void main(String[] args) { new Swing. Application("Swing. Application"); }} button

Handling Events • Every time the user types a character or pushes a mouse

Handling Events • Every time the user types a character or pushes a mouse button, an event occurs. • Any object can be notified of the event. • All the object has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source.

How to Implement an Event Handler • Every event handler requires three pieces of

How to Implement an Event Handler • Every event handler requires three pieces of code: 1. declaration of the event handler class that implements a listener interface or extends a class that implements a listener interface public class My. Class implements Action. Listener { 2. registration of an instance of the event handler class as a listener some. Component. add. Action. Listener(instance. Of. My. Class ); 3. providing code that implements the methods in the listener interface in the event handler class public void action. Performed(Action. Event e) {. . . //code that reacts to the action. . . }

A Simpler Event Example 1 public class Button. Click. Example extends JFrame Action. Listener

A Simpler Event Example 1 public class Button. Click. Example extends JFrame Action. Listener { JButton b = new JButton("Click me!"); public Button. Click. Example() { b. add. Action. Listener(this); get. Content. Pane(). add(b); pack(); set. Visible(true); } public void action. Performed(Action. Event e) { b. set. Background(Color. CYAN); } public static void main(String[] args) { new Button. Click. Example(); } } implements 2 3

Example Summary • (1) declares a class that implements a listener interface (i. e.

Example Summary • (1) declares a class that implements a listener interface (i. e. Action. Listener) • (2) registers an instance of this class with the event source • (3) defines the action to take when the event occurs

Image. Icon • Some Swing components can be decorated with an icon —a fixed-size

Image. Icon • Some Swing components can be decorated with an icon —a fixed-size image. • A Swing icon is an object that adheres to the Icon interface. • Swing provides a particularly useful implementation of the Icon interface: Image. Icon. • Image. Icon paints an icon from a GIF or a JPEG image.

Image. Icon Example import javax. swing. *; public class Image. Icon. Example extends JFrame

Image. Icon Example import javax. swing. *; public class Image. Icon. Example extends JFrame { public static void main(String[] args) { JFrame frame = new JFrame("Image. Icon Example"); Image. Icon icon = new Image. Icon("smallfrog. jpg"); JPanel panel = new JPanel(); JButton button = new JButton(icon); panel. add(button); frame. get. Content. Pane(). add(panel); frame. pack(); frame. set. Visible(true); } }

JText. Field Example (1) public class Celsius. Converter implements Action. Listener { JFrame converter.

JText. Field Example (1) public class Celsius. Converter implements Action. Listener { JFrame converter. Frame; JPanel converter. Panel; JText. Field temp. Celsius; JLabel celsius. Label, fahrenheit. Label; JButton convert. Temp; public Celsius. Converter() { converter. Frame = new JFrame("Convert Celsius to Fahrenheit"); converter. Panel = new JPanel(); converter. Panel. set. Layout(new Grid. Layout(2, 2)); add. Widgets(); converter. Frame. get. Content. Pane(). add(converter. Panel, Border. Layout. CENTER); converter. Frame. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE); converter. Frame. pack(); converter. Frame. set. Visible(true); }

JText. Field Example (2) private void add. Widgets() { temp. Celsius = new JText.

JText. Field Example (2) private void add. Widgets() { temp. Celsius = new JText. Field(2); celsius. Label = new JLabel("Celsius", Swing. Constants. LEFT); convert. Temp = new JButton("Convert. . . "); fahrenheit. Label = new JLabel("Fahrenheit", Swing. Constants. LEFT); convert. Temp. add. Action. Listener(this); converter. Panel. add(temp. Celsius); converter. Panel. add(celsius. Label); converter. Panel. add(convert. Temp); converter. Panel. add(fahrenheit. Label); }

JText. Field Example (3) public void action. Performed(Action. Event event) { int temp. Fahr

JText. Field Example (3) public void action. Performed(Action. Event event) { int temp. Fahr = (int)((Double. parse. Double( temp. Celsius. get. Text())) * 1. 8 + 32); fahrenheit. Label. set. Text(temp. Fahr + " Fahrenheit"); } public static void main(String[] args) { try { UIManager. set. Look. And. Feel( UIManager. get. Cross. Platform. Look. And. Feel. Class. Name() ); } catch(Exception e) {} Celsius. Converter converter = new Celsius. Converter(); } } // end Celcius. Converter class

JCheck. Box Example (1) public class Check. Box. Demo extends JPanel implements Action. Listener

JCheck. Box Example (1) public class Check. Box. Demo extends JPanel implements Action. Listener { JCheck. Box chin. Button; JCheck. Box glasses. Button; JCheck. Box hair. Button; JCheck. Box teeth. Button; JButton go. Button = new JButton("Go!"); public Check. Box. Demo() { chin. Button = new JCheck. Box("Chin"); chin. Button. set. Selected(true); glasses. Button = new JCheck. Box("Glasses"); glasses. Button. set. Selected(true); hair. Button = new JCheck. Box("Hair"); hair. Button. set. Selected(true); teeth. Button = new JCheck. Box("Teeth"); teeth. Button. set. Selected(true); go. Button. add. Action. Listener(this); set. Layout(new Grid. Layout(0, 1)); add(chin. Button); add(glasses. Button); add(hair. Button); add(teeth. Button); add(go. Button); }

JCheck. Box Example (2) public static void main(String s[]) { JFrame frame = new

JCheck. Box Example (2) public static void main(String s[]) { JFrame frame = new JFrame("Check. Box. Demo"); frame. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE ); frame. get. Content. Pane(). add(new Check. Box. Demo()); frame. pack(); frame. set. Visible(true); } } public void action. Performed(Action. Event e) { if (glasses. Button. is. Selected()) { System. out. println("Glasses = true"); } else { System. out. println("Glasses = false"); } System. exit(0); }

Example Summary • You may not want to be alerted every time the user

Example Summary • You may not want to be alerted every time the user selects or deselects a checkbox. • A more common use is to check the state of the button when the user clicks a button signifying that he/she is done and ready to advance.

JRadio. Button Example (1) public class Radio. Button. Demo extends JPanel implements Action. Listener

JRadio. Button Example (1) public class Radio. Button. Demo extends JPanel implements Action. Listener { String bird. String = "Bird"; String cat. String = "Cat"; String dog. String = "Dog"; String rabbit. String = "Rabbit"; String pig. String = "Pig"; JRadio. Button bird. Button = new JRadio. Button(bird. String); JRadio. Button cat. Button = new JRadio. Button(cat. String); JRadio. Button dog. Button = new JRadio. Button(dog. String); JRadio. Button rabbit. Button = new JRadio. Button(rabbit. String); JRadio. Button pig. Button = new JRadio. Button(pig. String); JButton go. Button = new JButton("Go!"); public Radio. Button. Demo() { bird. Button. set. Selected(true); Button. Group group = new Button. Group(); group. add(bird. Button); group. add(cat. Button); group. add(dog. Button); group. add(rabbit. Button); group. add(pig. Button); . . .

JRadio. Button Example (2) go. Button. add. Action. Listener(this); } set. Layout(new Grid. Layout(0,

JRadio. Button Example (2) go. Button. add. Action. Listener(this); } set. Layout(new Grid. Layout(0, 1)); add(bird. Button); add(cat. Button); add(dog. Button); add(rabbit. Button); add(pig. Button); add(go. Button); public static void main(String s[]) { JFrame frame = new JFrame("Radio. Button. Demo"); frame. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE); frame. get. Content. Pane(). add(new Radio. Button. Demo(), Border. Layout. CENTER); frame. pack(); frame. set. Visible(true); }

JRadio. Button Example (3) public void action. Performed(Action. Event e) { if (bird. Button.

JRadio. Button Example (3) public void action. Performed(Action. Event e) { if (bird. Button. is. Selected()) { System. out. println("User finally selected bird. "); System. exit(0); } if (cat. Button. is. Selected()) { System. out. println("User finally selected cat. "); System. exit(0); } if (dog. Button. is. Selected()) { System. out. println("User finally selected dog. "); System. exit(0); } } } if (rabbit. Button. is. Selected()) { System. out. println("User finally selected rabbit. "); System. exit(0); } if (pig. Button. is. Selected()) { System. out. println("User finally selected pig. "); System. exit(0); }

Example Summary • Button. Group ensures that only one radio button in the group

Example Summary • Button. Group ensures that only one radio button in the group can be selected at a time. • set. Selected sets initial state. (Good for defaults). • is. Selected checks the state of the button.

JCombo. Box • A combo box is a button that when pressed, presents a

JCombo. Box • A combo box is a button that when pressed, presents a list of items that can be selected.

JCombo. Box Example public class Combo. Box. Example implements Action. Listener { JCombo. Box

JCombo. Box Example public class Combo. Box. Example implements Action. Listener { JCombo. Box box; public Combo. Box. Example() { JFrame frame = new JFrame("Combo. Box. Example"); JPanel panel = new JPanel(); Set s = new Tree. Set(); s. add(new Integer(1)); s. add(new Integer(2)); notice use of collection s. add(new Integer(3)); box = new JCombo. Box(s. to. Array()); box. add. Action. Listener(this); panel. add(box); frame. get. Content. Pane(). add(panel); frame. pack(); frame. set. Visible(true); } public static void main(String[] args) { new Combo. Box. Example(); } public void action. Performed(Action. Event e) { if ("combo. Box. Changed". equals(e. get. Action. Command())) { System. out. println("User chose index " + box. get. Selected. Index()); } } }

Example Summary • Notice the use of the Set. • If we were to

Example Summary • Notice the use of the Set. • If we were to get the combo box choices from a file, we could prohibit duplicates by using a Set.

Dialogs - JOption. Pane • • • Dialogs are windows that are more limited

Dialogs - JOption. Pane • • • Dialogs are windows that are more limited than frames. Every dialog is dependent on a frame. When that frame is destroyed, so are its dependent dialogs. When the frame is iconified, its dependent dialogs disappear from the screen. When the frame is deiconified, its dependent dialogs return to the screen. To create simple dialogs, use the JOption. Pane class. The dialogs that JOption. Pane provides are modal. When a modal dialog is visible, it blocks user input to all other windows in the program.

JOption. Pane Examples // show an error dialog JOption. Pane. show. Message. Dialog(null, "alert",

JOption. Pane Examples // show an error dialog JOption. Pane. show. Message. Dialog(null, "alert", JOption. Pane. ERROR_MESSAGE);

JOption. Pane Examples // show Yes/No dialog int x = JOption. Pane. show. Confirm.

JOption. Pane Examples // show Yes/No dialog int x = JOption. Pane. show. Confirm. Dialog(null, "choose one", JOption. Pane. YES_NO_OPTION); System. out. println("User clicked button " + x);

JOption. Pane Examples // show input dialog String input. Value = JOption. Pane. show.

JOption. Pane Examples // show input dialog String input. Value = JOption. Pane. show. Input. Dialog("Please input “ + “a value"); System. out. println("User entered " + input. Value);

Layout Management • Layout managers control the size and arrangement of components in a

Layout Management • Layout managers control the size and arrangement of components in a container. • There are 6 common layout managers: – Border. Layout (demo’d) – Box. Layout – Flow. Layout (demo’d) – Grid. Bag. Layout – Grid. Layout (demo’d) – Card. Layout (demo’d)

Layout Management

Layout Management

Flow. Layout • Components are placed in a row from left to right in

Flow. Layout • Components are placed in a row from left to right in the order in which they are added. • A new row is started when no more components can fit in the current row. • The components are centered in each row by default. • The programmer can specify the size of both the vertical and horizontal gaps between the components. • Flow. Layout is the default layout for JPanels.

Flow. Layout Example public class Flow. Layout. Test extends JFrame { JButton b 1=new

Flow. Layout Example public class Flow. Layout. Test extends JFrame { JButton b 1=new JButton("Red"), b 2=new JButton("Green"), b 3=new JButton("Blue"), b 4=new JButton("Yellow"), b 5=new. JButton("Pink"); public Flow. Layout. Test() { set. Title("Flow. Layout Test"); Container pane = get. Content. Pane(); pane. set. Layout(new Flow. Layout()); set. Bounds(0, 0, 400, 100); pane. add(b 1); pane. add(b 2); pane. add(b 3); pane. add(b 4); pane. add(b 5); } public static void main(String args[]) { JFrame f = new Flow. Layout. Test(); f. set. Visible(true); } }

Border. Layout • Defines five locations where a component or components can be added:

Border. Layout • Defines five locations where a component or components can be added: – North, South, East, West, and Center • The programmer specifies the area in which a component should appear. • The relative dimensions of the areas are governed by the size of the components added to them.

Border. Layout North West Center South East

Border. Layout North West Center South East

Border-Layout Example public class Border. Layout. Test extends JFrame { JButton b 1=new JButton("Red"),

Border-Layout Example public class Border. Layout. Test extends JFrame { JButton b 1=new JButton("Red"), b 2=new JButton("Green"), b 3=new JButton("Blue"), b 4=new JButton("Yellow"), b 5=new JButton("Pink"); public Border. Layout. Test() { set. Title("Border. Layout Test"); Container pane = get. Content. Pane(); note extra parameter pane. set. Layout(new Border. Layout()); set. Bounds(0, 0, 400, 150); pane. add(b 1, "North"); pane. add(b 2, "South"); pane. add(b 3, "East"); pane. add(b 4, "West"); pane. add(b 5, "Center"); } public static void main(String args[]) { JFrame f = new Border. Layout. Test(); f. set. Visible(true); } }

Grid. Layout • Components are placed in a grid with a user-specified number of

Grid. Layout • Components are placed in a grid with a user-specified number of columns and rows. • Each component occupies exactly one grid cell. • Grid cells are filled left to right and top to bottom. • All cells in the grid are the same size. • Specifying zero for either rows or columns means any number of items can be placed in that row or column.

Grid. Layout Example public class Grid. Layout. Test extends JFrame { JButton b 1=new

Grid. Layout Example public class Grid. Layout. Test extends JFrame { JButton b 1=new JButton("Red"), b 2=new JButton("Green"), b 3=new JButton("Blue"), b 4=new JButton("Yellow"), b 5=new JButton("Pink"); public Grid. Layout. Test() { set. Title("Grid. Layout Test"); Container pane = get. Content. Pane(); pane. set. Layout(new Grid. Layout(2, 3)); set. Bounds(0, 0, 300, 100); pane. add(b 1); pane. add(b 2); pane. add(b 3); pane. add(b 4); pane. add(b 5); } public static void main(String args[]) { JFrame f = new Grid. Layout. Test(); f. set. Visible(true); } }

Card. Layout • Components governed by a card layout are "stacked" such that only

Card. Layout • Components governed by a card layout are "stacked" such that only one component is displayed on the screen at any one time. • Components are ordered according to the order in which they were added to the container. • Methods control which component is currently visible in the container. • Card. Layouts might be appropriate for wizards (with the Next >> buttons).

Card. Layout Example (1 of 3) public class Card. Layout. Test extends JFrame implements

Card. Layout Example (1 of 3) public class Card. Layout. Test extends JFrame implements Action. Listener { JButton b 1 = new JButton("Red"), b 2 = new JButton("Green"), b 3 = new JButton("Blue"), b 4 = new JButton("Yellow"), b 5 = new JButton("Pink"); Card. Layout lo = new Card. Layout(); Container pane; public Card. Layout. Test() { set. Title("Card. Layout Test"); pane = get. Content. Pane(); pane. set. Layout(lo); set. Bounds(0, 0, 200, 100); pane. add(b 1, "1"); pane. add(b 2, "2"); pane. add(b 3, "3"); pane. add(b 4, "4"); pane. add(b 5, "5"); b 1. add. Action. Listener(this); b 2. add. Action. Listener(this); b 3. add. Action. Listener(this); b 4. add. Action. Listener(this); b 5. add. Action. Listener(this); }

Card. Layout Example (2 of 3) // in the same file. . . public

Card. Layout Example (2 of 3) // in the same file. . . public void action. Performed(Action. Event e) { if (e. get. Source() == b 1) lo. next(pane); else if (e. get. Source() == b 2) lo. next(pane); else if (e. get. Source() == b 3) lo. next(pane); else if (e. get. Source() == b 4) lo. next(pane); else if (e. get. Source() == b 5) lo. next(pane); } public static void main(String args[]) { JFrame f = new Card. Layout. Test(); f. set. Visible(true); } } define the behavior when the user clicks a button: in this case, we advance to the next card

Card. Layout Example (3 of 3) Every arrow denotes a button click event. Our

Card. Layout Example (3 of 3) Every arrow denotes a button click event. Our code reacts to the click by advancing to the next card. Note that the cards cycle.

Other Swing Components • You can see all the other Swing components at http:

Other Swing Components • You can see all the other Swing components at http: //java. sun. com/products/jfc/tsc/articles/comp onent_gallery/index. html