AWT and Swing  Most GUI class libraries in C++ are platform specific Different hardware capabilities Different hardware capabilities Subtle differences.

Slides:



Advertisements
Similar presentations
Graphical User Interfaces (Part IV)
Advertisements

Java Software Development Paradigm Lecture # 12. Basics of GUI.
CS18000: Problem Solving and Object-Oriented Programming.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
1 Chapter 7 Graphics and Event Handling. 2 Overview The java.awt and javax.swing packages and their subpackages support graphics and event handling. Many.
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 16 Java Fundamentals Java2 Graphical User Interfaces.
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
Graphical User Interface Components: Part 1
Graphic User Interfaces Part 1. Typical GUI Screen from Microsoft Word What GUI “components” can you see? –Menus? Buttons? Labels? What else? –Anything.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
JCheckBox and JRadioButton State buttons –On/Off or true / false values –Java provides three types JToggleButton JCheckBox JRadioButton.
OOP (Java): GUI I/ OOP Objectives – –describe some of the GUI controls and their listeners; more appear in part 13 Semester 2,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Graphical User Interface Components: Part 1 Chapter 11.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
AWT and Swing Most GUI class libraries in C++ are platform specific
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.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Lec.10 (Chapter 8 & 9) GUI Jiang (Jen) ZHENG June 27 th, 2005.
1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement.
CS1054: Lecture 21 - Graphical User Interface. Graphical User Interfaces vs. Text User Interface.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
Swing Components. Introduction Swing – A set of GUI classes – Part of the Java's standard library –Much better than the previous library: AWT Abstract.
Graphical User Interface Components: Part 1 Chapter 11.
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
 Figure illustrates a hierarchy containing many event classes from the package java.awt.event.  Used with both AWT and Swing components.  Additional.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Graphical User Interface (GUI)
1 Chapter 13 – More GUI Components Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides users with basic.
1 Lecture 8: User Interface Components with Swing.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
Introduction to GUI in 1 Graphical User Interface 3 Nouf Almunyif.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
CSC 205 Programming II Lecture 5 AWT - I.
Welcome To java
Introduction to Graphics
Chap 7. Building Java Graphical User Interfaces
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
IFS410: Advanced Analysis and Design
AWT and Swing Most GUI class libraries in C++ are platform specific
Programming Graphical User Interface (GUI)
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

AWT and Swing  Most GUI class libraries in C++ are platform specific Different hardware capabilities Different hardware capabilities Subtle differences between the "look-and-feel" of various Windowing operating systems Subtle differences between the "look-and-feel" of various Windowing operating systems  Abstract Window Toolkit (AWT) is cross-platform Swing can observe various OS look-and-feel conventions Swing can observe various OS look-and-feel conventions

Common functionality/specific implementation approach Toolkit AWT Toolkit AWT | Button List JVM | | Native GUI Button Peer List Peer (Windows, Mac, X)  AWT GUI classes are platform-independent elements  Each AWT platform-specific toolkit comes with peer class implementing platform-specific behavior of its AWT class  Combining platform-independent AWT class with platform-specific peer class transforms generic, abstract windows behavior into specific, particular behavior

Peer classes at run-time class TestPeer { TestPeer() { Frame myFrame = new Frame("my Frame"); //create window Frame Frame myFrame = new Frame("my Frame"); //create window Frame Button myButton = new Button("my Button"); //create myButton Button myButton = new Button("my Button"); //create myButton myFrame.add("Center",myButton); //put myButton in myFrame myFrame.add("Center",myButton); //put myButton in myFrame myFrame.setVisible(true); //button appears in window on screen myFrame.setVisible(true); //button appears in window on screen //setVisible() creates peer objects for myFrame & myButton //setVisible() creates peer objects for myFrame & myButton ComponentPeer buttonPeer = myButton.getPeer(); //now works ComponentPeer buttonPeer = myButton.getPeer(); //now works }}  TestPeer first constructs a frame, then adds a button on the frame  setVisible method creates peer objects on platform  Last line now accesses myButton’s peer object  Peer classes are usually hidden from developers. Why?  In fact, in newer versions of JDK, getPeer() method is "deprecated"  Peer classes strongly discouraged for code maintenance purposes First, create a frame.Next, create a Button.Attach (add) myButton to myFrame.Now, peer objects exist. Note: getPeer() is now “deprecated.” Set myFrame and myButton visible, by creating platform-specific peer objects.

JDK 1.0 (circa 1996)  JDK 1.0 went a long way to implementing platform-independent GUI library  Bruce Eckel: it "produced a GUI that looks equally mediocre on all systems." Just 4 fonts Just 4 fonts Couldn’t access GUI of native OS Couldn’t access GUI of native OS Didn’t separate model and UI code cleanly Didn’t separate model and UI code cleanly

JDK 1.1 (circa 1998)  JDK 1.1 makes AWT more robust and extensible  Delegation-based event model separates user interface from problem domain Avoids cascaded if statements testing for object type required by first AWT Avoids cascaded if statements testing for object type required by first AWT Designates "listeners" of events triggered by problem domain objects Designates "listeners" of events triggered by problem domain objects Listeners implement the Observer design pattern Listeners implement the Observer design pattern  Other enhancements: button tool tips, cut/paste to the clipboard, popup menus, printing, etc. Adds supports for JavaBeans Adds supports for JavaBeans

JDK 1.2 (Swing)  JDK 1.2 adds Java Foundation Classes Swing is the GUI library for JDK 1.2 Swing is the GUI library for JDK 1.2 Much richer class library plus better integration with look and feel of GUI of OS Much richer class library plus better integration with look and feel of GUI of OS Eckel: "The ‘revision 3’ rule of software industry (a product isn’t good until revision 3) seems to hold true with programming languages as well." Eckel: "The ‘revision 3’ rule of software industry (a product isn’t good until revision 3) seems to hold true with programming languages as well."

Graphical Components button menus title barmenu barcombo box scroll bars

AWT class hierarchy Checkbox, Choice, Label, List, Scrollbar,ScrollPane, TextArea, TextField

Component and Container  Component contributes several public methods to all its subclasses: public void setSize(int width, int height); //set size in pixels public void setBackground(Color c); //see class Color for colors public void setVisible(boolean b); //see class Color for colors public void setVisible(boolean b); //Display on screen (creates peer)  Container is an abstract class: It cannot be instantiated; subclasses must implement some methods It cannot be instantiated; subclasses must implement some methods Container does implement some useful methods, including : Container does implement some useful methods, including : public Component add(Component comp); //put a Component in a Container public setLayout(LayoutManager mgr); public setLayout(LayoutManager mgr); //lay out components in some pattern

Window and Frame classes  A Window is a top-level window with no borders and no menubar It can generate a WindowOpened or a WindowClosed event, It can generate a WindowOpened or a WindowClosed event, to which a WindowListener or WindowAdapter can respond to which a WindowListener or WindowAdapter can respond  A Frame is a top-level window with a title and a border  Because it has more features, it can generate more events: WindowOpened, WindowClosing, WindowClosed, WindowIconified, WindowDeiconified, WindowActivated, WindowDeactivated  Respond to these events with a WindowListener  Once a subclass of Container has been constructed, it can add (attach) any AWT component within it, such as a Button, Label, TextField, or another Frame or Panel

A simple example A simple example //Demonstrates construction of a Container and a Button import java.awt.*; class Gui extends Frame { public Gui(String s) //constructor { super(s); //construct Frame part of Gui { super(s); //construct Frame part of Gui setBackground(Color.yellow); setBackground(Color.yellow); setLayout(new FlowLayout()); setLayout(new FlowLayout()); Button pushButton = new Button("press me"); Button pushButton = new Button("press me"); add(pushButton); add(pushButton); } } //class Gui class Ex_1 //Creates an instance of class Gui { public static void main(String[] args) { Gui screen = new Gui("Example 1"); { Gui screen = new Gui("Example 1"); screen.setSize(500,100); screen.setSize(500,100); screen.setVisible(true); screen.setVisible(true); } } //class Ex_1 Superclass does not most of the work of creating an instance of Gui. Modify properties of Gui.Create a button and attach it to Gui.Construct a Gui, set its size and make it visible. What does this program not do?

Responding to events Responding to events //Program to demonstrate action listeners and event handlers import java.awt.*; import java.awt.event.*; class Gui extends Frame implements ActionListener, WindowListener { public Gui(String s) //constructor { super(s); { super(s); setBackground(Color.yellow); setBackground(Color.yellow); setLayout(new FlowLayout()); setLayout(new FlowLayout()); addWindowListener(this); //listen for events on this Window addWindowListener(this); //listen for events on this Window Button pushButton = new Button("press me"); Button pushButton = new Button("press me"); add(pushButton); add(pushButton); pushButton.addActionListener(this); //listen for Button press pushButton.addActionListener(this); //listen for Button press } //define action for Button press //define action for Button press public void actionPerformed(ActionEvent event) public void actionPerformed(ActionEvent event) { final char bell = '\u0007'; { final char bell = '\u0007'; if (event.getActionCommand().equals("press me")) if (event.getActionCommand().equals("press me")) { System.out.print(bell); } { System.out.print(bell); } } //define methods in WindowListener interface //define methods in WindowListener interface public void windowClosing(WindowEvent event) { System.exit(0); } public void windowClosing(WindowEvent event) { System.exit(0); } public void windowClosed(WindowEvent event) {} //do nothing public void windowClosed(WindowEvent event) {} //do nothing public void windowDeiconified(WindowEvent event){} public void windowDeiconified(WindowEvent event){} public void windowIconified(WindowEvent event){} public void windowIconified(WindowEvent event){} public void windowActivated(WindowEvent event){} public void windowActivated(WindowEvent event){} public void windowDeactivated(WindowEvent event){} public void windowDeactivated(WindowEvent event){} public void windowOpened(WindowEvent event){} public void windowOpened(WindowEvent event){} } Attach a observer to “listen” for events that might occur on this window. Create a simple button, then add it to the Gui Frame. Attach an observer to listen to events on this button. Listen for these events that can occur on a Window. "press me" When the ActionEvent labeled "press me" occurs, print (ring) the bell.

Responding to events, continued  Uses event delegation model of JDK 1.1  When an event occurs, it generates an ActionEvent object ActionListener interface listens for a particular ActionEvent ActionListener interface listens for a particular ActionEvent Responds in its actionPerformed method Responds in its actionPerformed method  WindowListener interface observes events triggered by Window object, such as closing it, and responds in corresponding methods  Program now has a live Button: actionPerformed method rings a bell Also a live close window button, which performs System.exit(0) Also a live close window button, which performs System.exit(0)  Most Components in the AWT have corresponding Listeners

Adapter Classes  Time consuming to define all interface methods WindowListener has seven methods WindowListener has seven methods What if we only want to use one?What if we only want to use one? Required to define all methods in interfaceRequired to define all methods in interface  Adapter class i mplements an interface Does anyone recognize a design pattern here?Does anyone recognize a design pattern here? Default implementation ({ }, empty body) for all methodsDefault implementation ({ }, empty body) for all methods You then extend adapter class, You then extend adapter class, overriding methods for events you care about, such as windowClosing.overriding methods for events you care about, such as windowClosing. Has "is a" relationship with interface Has "is a" relationship with interface WindowAdapter is a WindowListenerWindowAdapter is a WindowListener MouseAdapter is a MouseListenerMouseAdapter is a MouseListener

Sketchpad example  See Sketchpad.java Sketchpad.java (H:\oose\java, java Sketchpad)

Layout managers  Sketchpad uses hard-coded layout, which depends on a 800x600 screen  JDK provides a set of generic layout manager classes Arrange Component objects within a Container object in predictable ways Arrange Component objects within a Container object in predictable ways FlowLayout (the default) add components one after another in rows: setLayout(new FlowLayout(FlowLayout.LEFT,10,10); for (int counter=1; counter <= 6; counter++) add(new Button(String.valueOf(counter))); add(new Button(String.valueOf(counter))); GridLayout places components in cells of a grid: setLayout(new GridLayout(3,2,5,5); //3 rows, 2 columns, 5 pixel gaps //3 rows, 2 columns, 5 pixel gaps for (int counter=1; counter <= 6; counter++) add(new Button(String.valueOf(counter))); BorderLayout arranges components using along four sides (North, South, East West) and Center positions

Swing overview  Defined in package javax.swing  Original GUI components from AWT in java.awt Heavyweight components - rely on local platform's windowing system for look and feel Heavyweight components - rely on local platform's windowing system for look and feel  Swing components are lightweight Not weighed down by GUI capabilities of platform Not weighed down by GUI capabilities of platform More portable than heavyweight components More portable than heavyweight components  Swing components allow programmer to specify look and feel Can change depending on platform Can change depending on platform Can be same across all platforms Can be same across all platforms

Swing component inheritance hierarchy java.awt.Component java.awt.Container java.lang.Object javax.swing.JComponent Component defines methods used in its subclasses (for example, paint and repaint) Container - collection of related components When using JFrame, add components to content pane (a Container) JComponent - superclass to most Swing components

Jcomponent features  Pluggable look and feel Can look like different platforms, at run-time Can look like different platforms, at run-time  Shortcut keys (mnemonics) Direct access to components through keyboard Direct access to components through keyboard  Common event handling If several components perform same actions If several components perform same actions  Tool tips Describe component when mouse rolls over it Describe component when mouse rolls over it

Menus Menu Bar JMenuBar() JMenuBar() add( JMenu ) add( JMenu )Menu JMenu( String ) add( JMenuItem ) JMenuBar mb = new JMenuBar(); //create a menu bar JMenu fileMenu = new JMenu (“File”); //create a menu mb.add( fileMenu );//add menu to menu bar setMenuBar( mb ); // add a menu bar to frame fileMenu.setMnemonic( KeyEvent.VK_F ); // add a hotkey to menu JMenuItem miOpen = new JMenuItem( “Open...”, KeyEvent.VK_O ); JMenuItem miExit = new JMenuItem( “Exit” ); fileMenu.add( miOpen ); // add a menu item fileMenu.addSeparator(); // add a menu separator fileMenu.add( miExit ); JMenuItem( String ) JMenuItem( String,int )

JLabel  Labels Provide text instructions on a GUI Provide text instructions on a GUI Read-only text Read-only text Programs rarely change a label's contents Programs rarely change a label's contents Class JLabel (subclass of JComponent ) Class JLabel (subclass of JComponent )  Methods Can declare label text in constructor Can declare label text in constructor myLabel.setToolTipText( "Text" ) myLabel.setToolTipText( "Text" ) Displays "Text" in a tool tip when mouse over labelDisplays "Text" in a tool tip when mouse over label myLabel.setText( "Text" ) myLabel.setText( "Text" ) myLabel.getText() myLabel.getText()

JLabel  Icon Object that implements interface Icon Object that implements interface Icon One class is ImageIcon (.gif and.jpeg images) One class is ImageIcon (.gif and.jpeg images) Assumed same directory as programAssumed same directory as program Display an icon with JLabel ’s setIcon method Display an icon with JLabel ’s setIcon method myLabel.setIcon( myIcon );myLabel.setIcon( myIcon ); myLabel.getIcon //returns current IconmyLabel.getIcon //returns current Icon 24 Icon bug = new ImageIcon( "bug1.gif" ); 33 label3.setIcon( bug );

1// Fig. 12.4: LabelTest.java 2// Demonstrating the JLabel class. 3import javax.swing.*; 4import java.awt.*; 5import java.awt.event.*; 6 7public class LabelTest extends JFrame { 8 private JLabel label1, label2, label3; 9 10 public LabelTest() 11 { 12 super( "Testing JLabel" ); Container c = getContentPane(); 15 c.setLayout( new FlowLayout() ); // JLabel constructor with a string argument label1 = new JLabel( "Label with text" ); label1.setToolTipText( "This is label1" ); 20 c.add( label1 ); // JLabel constructor with string, Icon and 23 // alignment arguments Icon bug = new ImageIcon( "bug1.gif" ); label2 = new JLabel( "Label with text and icon", 26 bug, SwingConstants.LEFT ); 27 label2.setToolTipText( "This is label2" ); 28 c.add( label2 ); 29 Create a Container object, to which we attach JLabel objects (subclass of JComponent ). Initialize text in JLabel constructor.Create a new ImageIcon (assumed to be in same directory as program). Set ImageIcon and alignment of text in JLabel constructor. Set the tool tip text, and attach component to Container c.

JButton  Methods of class JButton Constructors Constructors JButton myButton = new JButton( "Label" ); JButton myButton = new JButton( "Label", myIcon ); setRolloverIcon( myIcon ) setRolloverIcon( myIcon ) Sets image to display when mouse over buttonSets image to display when mouse over button  Class ActionEvent getActionCommand returns label of button that generated eventreturns label of button that generated event Icon bug1 = new ImageIcon( "bug1.gif" ); fancyButton = new JButton( "Fancy Button", bug1 ); fancyButton.setRolloverIcon( bug2 );

JCheckBox  When JCheckBox changes ItemEvent generated ItemEvent generated Handled by an ItemListener, which must define itemStateChangedHandled by an ItemListener, which must define itemStateChanged Register handlers with with addItemListener Register handlers with with addItemListener  Class ItemEvent getStateChange getStateChange Returns ItemEvent.SELECTED or ItemEvent.DESELECTEDReturns ItemEvent.SELECTED or ItemEvent.DESELECTED private class CheckBoxHandler implements ItemListener { public void itemStateChanged( ItemEvent e )

1. import 1.1 Declarations 1.2 Initialize JCheckBox es 1.3 Register event handler 1// Fig : CheckBoxTest.java 2// Creating Checkbox buttons. 3import java.awt.*; 4import java.awt.event.*; 5import javax.swing.*; 6 7public class CheckBoxTest extends JFrame { 8 private JTextField t; 9 private JCheckBox bold, italic; public CheckBoxTest() 12 { 13 super( "JCheckBox Test" ); Container c = getContentPane(); 16 c.setLayout(new FlowLayout()); t = new JTextField( "Watch the font style change", 20 ); 19 t.setFont( new Font( "TimesRoman", Font.PLAIN, 14 ) ); 20 c.add( t ); // create checkbox objects bold = new JCheckBox( "Bold" ); 24 c.add( bold ); italic = new JCheckBox( "Italic" ); 27 c.add( italic ); CheckBoxHandler handler = new CheckBoxHandler(); 30 bold.addItemListener( handler ); Create JCheckBox es

31 italic.addItemListener( handler ); addWindowListener( 34 new WindowAdapter() { 35 public void windowClosing( WindowEvent e ) 36 { 37 System.exit( 0 ); 38 } 39 } 40 ); setSize( 275, 100 ); 43 show(); 44 } public static void main( String args[] ) 47 { 48 new CheckBoxTest(); 49 } private class CheckBoxHandler implements ItemListener { 52 private int valBold = Font.PLAIN; 53 private int valItalic = Font.PLAIN; public void itemStateChanged( ItemEvent e ) 56 { 57 if ( e.getSource() == bold ) if ( e.getStateChange() == ItemEvent.SELECTED ) 59 valBold = Font.BOLD; 60 else 61 valBold = Font.PLAIN; Because CheckBoxHandler implements ItemListener, it must define method itemStateChanged getStateChange returns ItemEvent.SELECTED or ItemEvent.DESELECTED

JRadioButton  Radio buttons Have two states: selected and deselected Have two states: selected and deselected Normally appear as a group Normally appear as a group Only one radio button in group selected at timeOnly one radio button in group selected at time Selecting one button forces the other buttons offSelecting one button forces the other buttons off Mutually exclusive options Mutually exclusive options ButtonGroup - maintains logical relationship between radio buttons ButtonGroup - maintains logical relationship between radio buttons  Class JRadioButton Constructor Constructor JRadioButton( "Label", selected )JRadioButton( "Label", selected ) If selected true, JRadioButton initially selectedIf selected true, JRadioButton initially selected

1. import 1.1 Declarations 1.2 Initialization 1// Fig : RadioButtonTest.java 2// Creating radio buttons using ButtonGroup and JRadioButton. 3import java.awt.*; 4import java.awt.event.*; 5import javax.swing.*; 6 7public class RadioButtonTest extends JFrame { 8 private JTextField t; 9 private Font plainFont, boldFont, 10 italicFont, boldItalicFont; 11 private JRadioButton plain, bold, italic, boldItalic; 12 private ButtonGroup radioGroup; public RadioButtonTest() 15 { 16 super( "RadioButton Test" ); Container c = getContentPane(); 19 c.setLayout( new FlowLayout() ); t = new JTextField( "Watch the font style change", 25 ); 22 c.add( t ); // Create radio buttons 25 plain = new JRadioButton( "Plain", true ); 26 c.add( plain ); 27 bold = new JRadioButton( "Bold", false); 28 c.add( bold ); 29 italic = new JRadioButton( "Italic", false ); 30 c.add( italic ); Initialize radio buttons. Only one is initially selected.

31 boldItalic = new JRadioButton( "Bold/Italic", false ); 32 c.add( boldItalic ); // register events 35 RadioButtonHandler handler = new RadioButtonHandler(); 36 plain.addItemListener( handler ); 37 bold.addItemListener( handler ); 38 italic.addItemListener( handler ); 39 boldItalic.addItemListener( handler ); // create logical relationship between JRadioButtons radioGroup = new ButtonGroup(); radioGroup.add( plain ); 44 radioGroup.add( bold ); 45 radioGroup.add( italic ); 46 radioGroup.add( boldItalic ); plainFont = new Font( "TimesRoman", Font.PLAIN, 14 ); 49 boldFont = new Font( "TimesRoman", Font.BOLD, 14 ); 50 italicFont = new Font( "TimesRoman", Font.ITALIC, 14 ); 51 boldItalicFont = 52 new Font( "TimesRoman", Font.BOLD + Font.ITALIC, 14 ); 53 t.setFont( plainFont ); setSize( 300, 100 ); 56 show(); 57 } 58 Create a ButtonGroup. Only one radio button in the group may be selected at a time. Method add adds radio buttons to the ButtonGroup

JList  List Displays series of items Displays series of items may select one or more items may select one or more items  Class JList Constructor JList( arrayOfNames ) Constructor JList( arrayOfNames ) Takes array of Objects ( String s) to display in listTakes array of Objects ( String s) to display in list setVisibleRowCount( n ) setVisibleRowCount( n ) Displays n items at a timeDisplays n items at a time Does not provide automatic scrollingDoes not provide automatic scrolling

30 // create a list with the items in the colorNames array colorList = new JList( colorNames ); 32 colorList.setVisibleRowCount( 5 ); // do not allow multiple selections colorList.setSelectionMode( 36 ListSelectionModel.SINGLE_SELECTION ); // add a JScrollPane containing the JList 39 // to the content pane c.add( new JScrollPane( colorList ) ); // set up event handler 43 colorList.addListSelectionListener( 44 new ListSelectionListener() { 45 public void valueChanged( ListSelectionEvent e ) 46 { c.setBackground( 48 colors[ colorList.getSelectedIndex() ] ); 49 } 50 } 51 ); setSize( 350, 150 ); 54 show(); 55 } public static void main( String args[] ) 58 { 59 ListTest app = new ListTest(); Initialize JList with array of String s, and show 5 items at a time. Make the JList a single- selection list. Create a new JScrollPane object, initialize it with a JList, and attach it to the content pane. Change the color according to the item selected (use getSelectedIndex ).

1// Fig : MouseDetails.java2// Demonstrating mouse clicks and 3// distinguishing between mouse buttons. 4import javax.swing.*; 5import java.awt.*; 6import java.awt.event.*; 7 8public class MouseDetails extends JFrame { 9 private String s = ""; 10 private int xPos, yPos; public MouseDetails() 13 { 14 super( "Mouse clicks and buttons" ); addMouseListener( new MouseClickHandler() ); setSize( 350, 150 ); 19 show(); 20 } public void paint( Graphics g ) 23 { 24 g.drawString( [" + xPos + ", " + yPos + "]", 25 xPos, yPos ); 26 } 27 Another example, illustrating mouse events in AWT and Swing Add a listener for a mouse click.

28 public static void main( String args[] ) 29 { 30 MouseDetails app = new MouseDetails(); app.addWindowListener( 33 new WindowAdapter() { 34 public void windowClosing( WindowEvent e ) 35 { 36 System.exit( 0 ); 37 } 38 } 39 ); 40 } // inner class to handle mouse events private class MouseClickHandler extends MouseAdapter { 44 public void mouseClicked( MouseEvent e ) 45 { 46 xPos = e.getX(); 47 yPos = e.getY(); String s = "Clicked " + e.getClickCount() + " time(s)"; if ( e.isMetaDown() ) // Right mouse button 53 s += " with right mouse button"; 54 else if ( e.isAltDown() ) // Middle mouse button 55 s += " with center mouse button"; 56 else // Left mouse button 57 s += " with left mouse button"; 58 Use a named inner class as the event handler. Can still inherit from MouseAdapter ( extends MouseAdapter ). Use getClickCount, isAltDown, and isMetaDown to determine the String to use.

Program Output setTitle( s ); // set the title bar of the window 60 repaint(); 61 } 62 } 63} Set the Frame’s title bar.

Learn more about Swing compenents  wing/components/componentlist.html

Good and bad programming practices with AWT  Separate user interface logic from "business logic" or model  AWT 1.1 "listeners" designed for this purpose; inner classes facilitate it further  Separation.java example illustrates this approach: Separation.java  class BusinessLogic knows nothing about UI;  class Separation keeps track of all UI details and talks to BusinessLogic through its public interface. How is this design loosely coupled? How does it support reuse? How does it support legacy code?  Also note use of inner classes for all "listeners" nested within Separation  Contrast code of badidea1.java: look at code in actionPerformed: badidea1.java public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == b1) System.out.println("Button 1 pressed"); else if (source == b2) System.out.println("Button 2 pressed"); else System.out.println("Something else"); }  badidea2.java improves on things by using adapters, but...  badidea2.java improves on things by using adapters, but... badidea2.java  Why is the cascaded if above a bad idea?

JThankYou

Eclipse Widgets  Standard Widget Toolkit (SWT) GUI toolkit released in November 2001 GUI toolkit released in November 2001 Initially designed for the Eclipse IDE Initially designed for the Eclipse IDE “Best of both worlds” approach – use native functionality when available, and Java implementation when unavailable “Best of both worlds” approach – use native functionality when available, and Java implementation when unavailable Takes on the appearance and behavior of the native platform Takes on the appearance and behavior of the native platform The code YOU write will be portable for all the platforms that have SWT implementations The code YOU write will be portable for all the platforms that have SWT implementations - SWT home page - SWT home pagehttp://

GUI Builders  Netbeans (Sun)  JBuilder (Borland)  Eclipse (IBM and others) Visual Editor Visual Editor Help  Software Updates  Find and Install…Help  Software Updates  Find and Install…

Eclipse Visual Editor