SlideShare a Scribd company logo
1 of 43
AWT- Abstract Window Tool KitAWT- Abstract Window Tool Kit
SwingSwing
Presentation By: Shehrevar Davierwala
http://sites.google.com/site/techwizardin
www.authorstream.com/shehrevard
AWT and SwingAWT and Swing
 Most GUI class libraries in C++ are platform specificMost GUI class libraries in C++ are platform specific

Different hardware capabilitiesDifferent hardware capabilities

Subtle differences between the "look-and-feel" of variousSubtle differences between the "look-and-feel" of various
Windowing operating systemsWindowing operating systems
 Abstract Window Toolkit (AWT) is cross-platformAbstract Window Toolkit (AWT) is cross-platform

Swing can observe various OS look-and-feel conventionsSwing can observe various OS look-and-feel conventions
Common functionality/specific implementation approachCommon functionality/specific implementation approach
Toolkit -------------------------------------------------- AWTToolkit -------------------------------------------------- AWT
-----------|-----------------------|------------
Button List JVMButton List JVM
| | Native GUI| | Native GUI
Button Peer List Peer (Windows, Mac, X)Button Peer List Peer (Windows, Mac, X)
 AWT GUI classes are platform-independent elementsAWT GUI classes are platform-independent elements
 Each AWT platform-specific toolkit comes withEach AWT platform-specific toolkit comes with peerpeer classclass
implementing platform-specific behavior of its AWT classimplementing platform-specific behavior of its AWT class
 Combining platform-independent AWT class withCombining platform-independent AWT class with
platform-specific peer class transforms generic, abstract windowsplatform-specific peer class transforms generic, abstract windows
behavior into specific, particular behaviorbehavior into specific, particular behavior
Peer classes at run-timePeer classes at run-time
class TestPeer {class TestPeer {
TestPeer() {TestPeer() {
Frame myFrame = new Frame("my Frame"); //create window FrameFrame myFrame = new Frame("my Frame"); //create window Frame
Button myButton = new Button("my Button"); //create myButtonButton myButton = new Button("my Button"); //create myButton
myFrame.add("Center",myButton); //put myButton in myFramemyFrame.add("Center",myButton); //put myButton in myFrame
myFrame.setVisible(true); //button appears in window on screenmyFrame.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 worksComponentPeer buttonPeer = myButton.getPeer(); //now works
}}
}}
 TestPeer first constructs a frame, then adds a button on the frameTestPeer first constructs a frame, then adds a button on the frame
 setVisible method creates peer objects on platformsetVisible method creates peer objects on platform
 Last line now accesses myButton’s peer objectLast line now accesses myButton’s peer object
 Peer classes are usually hidden from developers. Why?Peer classes are usually hidden from developers. Why?
 In fact, in newer versions of JDK, getPeer() method is "deprecated"In fact, in newer versions of JDK, getPeer() method is "deprecated"
 Peer classes strongly discouraged for code maintenance purposesPeer 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 (circa 1996)
 JDK 1.0 went a long way to implementingJDK 1.0 went a long way to implementing
platform-independent GUI libraryplatform-independent GUI library
 Bruce Eckel: it "produced a GUI that looksBruce Eckel: it "produced a GUI that looks
equally mediocre on all systems."equally mediocre on all systems."

Just 4 fontsJust 4 fonts

Couldn’t access GUI of native OSCouldn’t access GUI of native OS

Didn’t separate model and UI code cleanlyDidn’t separate model and UI code cleanly
JDK 1.1 (circa 1998)JDK 1.1 (circa 1998)
 JDK 1.1 makes AWT more robust and extensibleJDK 1.1 makes AWT more robust and extensible
 Delegation-based event model separates userDelegation-based event model separates user
interface from problem domaininterface from problem domain

Avoids cascaded if statements testing for object typeAvoids cascaded if statements testing for object type
required by first AWTrequired by first AWT

Designates "listeners" of events triggered by problemDesignates "listeners" of events triggered by problem
domain objectsdomain objects

Listeners implement the Observer design patternListeners implement the Observer design pattern
 Other enhancements: button tool tips, cut/pasteOther enhancements: button tool tips, cut/paste
to the clipboard, popup menus, printing, etc.to the clipboard, popup menus, printing, etc.

Adds supports for JavaBeansAdds supports for JavaBeans
JDK 1.2 (Swing)JDK 1.2 (Swing)
 JDK 1.2 adds Java Foundation ClassesJDK 1.2 adds Java Foundation Classes

Swing is the GUI library for JDK 1.2Swing is the GUI library for JDK 1.2

Much richer class library plus better integrationMuch richer class library plus better integration
with look and feel of GUI of OSwith look and feel of GUI of OS

Eckel: "The ‘revision 3’ rule of software industryEckel: "The ‘revision 3’ rule of software industry
(a product isn’t good until revision 3) seems to(a product isn’t good until revision 3) seems to
hold true with programming languages as well."hold true with programming languages as well."
Graphical ComponentsGraphical Componentsbutton menus title bar menu bar combo box
scroll
bars
AWT class hierarchyAWT class hierarchy
Checkbox, Choice,
Label, List,
Scrollbar,ScrollPane,
TextArea, TextField
Component and ContainerComponent and Container
 ComponentComponent contributes several public methods to all its subclasses:contributes several public methods to all its subclasses:
public void setSize(int width, int height);public void setSize(int width, int height);
//set size in pixels//set size in pixels
public void setBackground(Color c);public void setBackground(Color c);
//see class Color for colors//see class Color for colors
public void setVisible(boolean b);public void setVisible(boolean b);
//Display on screen (creates peer)//Display on screen (creates peer)
 ContainerContainer is an abstract class:is an abstract class:

It cannot be instantiated; subclasses must implement some methodsIt cannot be instantiated; subclasses must implement some methods

ContainerContainer does implement some useful methods, includingdoes implement some useful methods, including::
public Component add(Component comp);public Component add(Component comp);
//put a Component in a Container//put a Component in a Container
public setLayout(LayoutManager mgr);public setLayout(LayoutManager mgr);
//lay out components in some pattern//lay out components in some pattern
Window and Frame classesWindow and Frame classes
 AA WindowWindow is a top-level window with no borders and no menubaris a top-level window with no borders and no menubar

It can generate aIt can generate a WindowOpenedWindowOpened or aor a WindowClosedWindowClosed event,event,
to which ato which a WindowListenerWindowListener oror WindowAdapterWindowAdapter can respondcan respond
 AA FrameFrame is a top-level window with a title and a borderis a top-level window with a title and a border
 Because it has more features, it can generate more events:Because it has more features, it can generate more events:
WindowOpened, WindowClosing, WindowClosed,WindowOpened, WindowClosing, WindowClosed,
WindowIconified, WindowDeiconified,WindowIconified, WindowDeiconified,
WindowActivated, WindowDeactivatedWindowActivated, WindowDeactivated
 Respond to these events with aRespond to these events with a WindowListenerWindowListener
 Once a subclass of Container has been constructed, it canOnce a subclass of Container has been constructed, it can addadd
(attach) any AWT component within it, such as a Button, Label,(attach) any AWT component within it, such as a Button, Label,
TextField, or another Frame or PanelTextField, or another Frame or Panel
A simple exampleA simple example
//Demonstrates construction of a Container and a Button//Demonstrates construction of a Container and a Button
import java.awt.*;import java.awt.*;
class Gui extends Frameclass Gui extends Frame
{{
public Gui(String s)public Gui(String s) //constructor//constructor
{ super(s);{ super(s); //construct Frame part of Gui//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 Gui
class Ex_1class Ex_1 //Creates an instance of class Gui//Creates an instance of class Gui
{ public static void main(String[] args){ 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} //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 eventsResponding to events
//Program to demonstrate action listeners and event handlers//Program to demonstrate action listeners and event handlers
import java.awt.*;import java.awt.*;
import java.awt.event.*;import java.awt.event.*;
class Gui extends Frame implements ActionListener, WindowListenerclass Gui extends Frame implements ActionListener, WindowListener
{ public Gui(String s) //constructor{ 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 WindowaddWindowListener(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 presspushButton.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 nothingpublic 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.
When the ActionEvent
labeled "press me""press me" occurs,
print (ring) the bell.
Responding to events, continuedResponding to events, continued
 Uses event delegation model of JDK 1.1Uses event delegation model of JDK 1.1
 When an event occurs, it generates anWhen an event occurs, it generates an ActionEventActionEvent objectobject

ActionListenerActionListener interface listens for a particularinterface listens for a particular ActionEventActionEvent

Responds in itsResponds in its actionPerformedactionPerformed methodmethod
 WindowListenerWindowListener interface observes events triggered byinterface observes events triggered by
WindowWindow object, such as closing it, and responds inobject, such as closing it, and responds in
corresponding methodscorresponding methods
 Program now has a live Button:Program now has a live Button: actionPerformedactionPerformed methodmethod
rings a bellrings a bell

Also a live close window button, which performsAlso a live close window button, which performs System.exit(0)System.exit(0)
 Most Components in the AWT have corresponding ListenersMost Components in the AWT have corresponding Listeners
Adapter ClassesAdapter Classes
 Time consuming to define all interface methodsTime consuming to define all interface methods

WindowListenerWindowListener has seven methodshas 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 iAdapter class implements an interfacemplements 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 asoverriding methods for events you care about, such as
windowClosingwindowClosing..

Has "is a" relationship with interfaceHas "is a" relationship with interface
• WindowAdapterWindowAdapter is ais a WindowListenerWindowListener
• MouseAdapterMouseAdapter is ais a MouseListenerMouseListener
Layout managersLayout managers
 Sketchpad uses hard-coded layout, which depends on a 800x600 screenSketchpad uses hard-coded layout, which depends on a 800x600 screenJDK provides a set of genericJDK provides a set of generic layout managerlayout manager classesclasses
• Arrange Component objects within a Container object in predictable waysArrange Component objects within a Container object in predictable ways
FlowLayout (the default) add components one after another in rows:FlowLayout (the default) add components one after another in rows:
setLayout(new FlowLayout(FlowLayout.LEFT,10,10);setLayout(new FlowLayout(FlowLayout.LEFT,10,10);
for (int counter=1; counter <= 6; counter++)for (int counter=1; counter <= 6; counter++)
add(new Button(String.valueOf(counter)));add(new Button(String.valueOf(counter)));
1 2 31 2 3
4 5 64 5 6
GridLayout places components in cells of a grid:GridLayout places components in cells of a grid:
setLayout(new GridLayout(3,2,5,5);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++)for (int counter=1; counter <= 6; counter++)
add(new Button(String.valueOf(counter)));add(new Button(String.valueOf(counter)));
1 21 2
3 43 4
5 65 6
BorderLayout arranges components using along four sidesBorderLayout arranges components using along four sides
(North, South, East West) and Center positions(North, South, East West) and Center positions
Swing overviewSwing overview
 Defined in packageDefined in package javax.swingjavax.swing
 Original GUI components from AWT inOriginal GUI components from AWT in java.awtjava.awt

HeavyweightHeavyweight components - rely on local platform'scomponents - rely on local platform's
windowing system for look and feelwindowing system for look and feel
 Swing components areSwing components are lightweightlightweight

Not weighed down by GUI capabilities of platformNot weighed down by GUI capabilities of platform

More portable than heavyweight componentsMore portable than heavyweight components
 Swing components allow programmer to specify look and feelSwing components allow programmer to specify look and feel

Can change depending on platformCan change depending on platform

Can be same across all platformsCan be same across all platforms
Swing component inheritance hierarchySwing 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 featuresJcomponent features
 Pluggable look and feelPluggable look and feel

Can look like different platforms, at run-timeCan look like different platforms, at run-time
 Shortcut keys (mnemonics)Shortcut keys (mnemonics)

Direct access to components through keyboardDirect access to components through keyboard
 Common event handlingCommon event handling

If several components perform same actionsIf several components perform same actions
 Tool tipsTool tips

Describe component when mouse rolls over itDescribe component when mouse rolls over it
MenusMenus
Menu BarMenu Bar

JMenuBar()JMenuBar()

add( JMenu )add( JMenu )
MenuMenu

JMenu( String )JMenu( String )

add( JMenuItem )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 )
JLabelJLabel
 LabelsLabels

Provide text instructions on a GUIProvide text instructions on a GUI

Read-only textRead-only text

Programs rarely change a label's contentsPrograms rarely change a label's contents

ClassClass JLabelJLabel (subclass of(subclass of JComponentJComponent))
 MethodsMethods

Can declare label text in constructorCan declare label text in constructor

myLabel.setToolTipText( "Text" )myLabel.setToolTipText( "Text" )
• DisplaysDisplays "Text""Text" in a tool tip when mouse over labelin a tool tip when mouse over label

myLabel.setText( "Text" )myLabel.setText( "Text" )

myLabel.getText()myLabel.getText()
JLabelJLabel
 IconIcon

Object that implements interfaceObject that implements interface IconIcon

One class isOne class is ImageIconImageIcon ((.gif.gif andand .jpeg.jpeg images)images)
• Assumed same directory as programAssumed same directory as program

Display an icon withDisplay an icon with JLabelJLabel’s’s setIconsetIcon methodmethod
• 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.
3 import javax.swing.*;
4 import java.awt.*;
5 import java.awt.event.*;
6
7 public class LabelTest extends JFrame {
8 private JLabel label1, label2, label3;
9
10 public LabelTest()
11 {
12 super( "Testing JLabel" );
13
1414 Container c = getContentPane();
15 c.setLayout( new FlowLayout() );
16
17 // JLabel constructor with a string argument
1818 label1 = new JLabel( "Label with text" );
1919 label1.setToolTipText( "This is label1" );
20 c.add( label1 );
21
22 // JLabel constructor with string, Icon and
23 // alignment arguments
2424 Icon bug = new ImageIcon( "bug1.gif" );
2525 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.
JButtonJButton
 Methods of classMethods of class JButtonJButton

ConstructorsConstructors
JButton myButton = new JButton( "Label" );JButton myButton = new JButton( "Label" );
JButton myButton = new JButton( "Label", myIcon );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
 ClassClass ActionEvent getActionCommandActionEvent 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 );
JCheckBoxJCheckBox
 WhenWhen JCheckBoxJCheckBox changeschanges

ItemEventItemEvent generatedgenerated
• Handled by anHandled by an ItemListenerItemListener, which must define, which must define
itemStateChangeditemStateChanged

Register handlers with withRegister handlers with with addItemListeneraddItemListener
 ClassClass ItemEventItemEvent

getStateChangegetStateChange
• ReturnsReturns ItemEvent.SELECTEDItemEvent.SELECTED oror
ItemEvent.DESELECTEDItemEvent.DESELECTED
private class CheckBoxHandler implements ItemListener {
public void itemStateChanged( ItemEvent e )
1.1. importimport
1.1 Declarations1.1 Declarations
1 // Fig. 12.12: CheckBoxTest.java
2 // Creating Checkbox buttons.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class CheckBoxTest extends JFrame {
8 private JTextField t;
9 private JCheckBox bold, italic;
10
11 public CheckBoxTest()
12 {
13 super( "JCheckBox Test" );
14
15 Container c = getContentPane();
16 c.setLayout(new FlowLayout());
17
18 t = new JTextField( "Watch the font style change", 20 );
19 t.setFont( new Font( "TimesRoman", Font.PLAIN, 14 ) );
20 c.add( t );
21
22 // create checkbox objects
2323 bold = new JCheckBox( "Bold" );
24 c.add( bold );
25
26 italic = new JCheckBox( "Italic" );
27 c.add( italic );
28
29 CheckBoxHandler handler = new CheckBoxHandler();
30 bold.addItemListener( handler );
Create JCheckBoxes
31 italic.addItemListener( handler );
32
33 addWindowListener(
34 new WindowAdapter() {
35 public void windowClosing( WindowEvent e )
36 {
37 System.exit( 0 );
38 }
39 }
40 );
41
42 setSize( 275, 100 );
43 show();
44 }
45
46 public static void main( String args[] )
47 {
48 new CheckBoxTest();
49 }
50
5151 private class CheckBoxHandler implements ItemListener {
52 private int valBold = Font.PLAIN;
53 private int valItalic = Font.PLAIN;
54
55 public void itemStateChanged( ItemEvent e )
56 {
57 if ( e.getSource() == bold )
5858 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
JRadioButtonJRadioButton
 Radio buttonsRadio buttons

Have two states: selected and deselectedHave two states: selected and deselected

Normally appear as a groupNormally 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 optionsMutually exclusive options

ButtonGroupButtonGroup - maintains logical relationship between- maintains logical relationship between
radio buttonsradio buttons
 ClassClass JRadioButtonJRadioButton

ConstructorConstructor
• JRadioButton( "Label", selected )JRadioButton( "Label", selected )
• If selectedIf selected truetrue,, JRadioButtonJRadioButton initially selectedinitially selected
1.1. importimport
1.1 Declarations1.1 Declarations
1 // Fig. 12.12: RadioButtonTest.java
2 // Creating radio buttons using ButtonGroup and JRadioButton.
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public 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;
13
14 public RadioButtonTest()
15 {
16 super( "RadioButton Test" );
17
18 Container c = getContentPane();
19 c.setLayout( new FlowLayout() );
20
21 t = new JTextField( "Watch the font style change", 25 );
22 c.add( t );
23
24 // 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 );
33
34 // register events
35 RadioButtonHandler handler = new RadioButtonHandler();
36 plain.addItemListener( handler );
37 bold.addItemListener( handler );
38 italic.addItemListener( handler );
39 boldItalic.addItemListener( handler );
40
41 // create logical relationship between JRadioButtons
4242 radioGroup = new ButtonGroup();
4343 radioGroup.add( plain );
44 radioGroup.add( bold );
45 radioGroup.add( italic );
46 radioGroup.add( boldItalic );
47
48 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 );
54
55 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
JListJList
 ListList

Displays series of itemsDisplays series of items

may select one or more itemsmay select one or more items
 ClassClass JListJList

ConstructorConstructor JList( arrayOfNames )JList( arrayOfNames )
• Takes array ofTakes array of ObjectsObjects ((StringStrings) to display in lists) to display in list

setVisibleRowCount( n )setVisibleRowCount( n )
• DisplaysDisplays nn items at a timeitems at a time
• Does not provide automatic scrollingDoes not provide automatic scrolling
30 // create a list with the items in the colorNames array
3131 colorList = new JList( colorNames );
32 colorList.setVisibleRowCount( 5 );
33
34 // do not allow multiple selections
3535 colorList.setSelectionMode(
36 ListSelectionModel.SINGLE_SELECTION );
37
38 // add a JScrollPane containing the JList
39 // to the content pane
4040 c.add( new JScrollPane( colorList ) );
41
42 // set up event handler
43 colorList.addListSelectionListener(
44 new ListSelectionListener() {
45 public void valueChanged( ListSelectionEvent e )
46 {
4747 c.setBackground(
48 colors[ colorList.getSelectedIndex() ] );
49 }
50 }
51 );
52
53 setSize( 350, 150 );
54 show();
55 }
56
57 public static void main( String args[] )
58 {
59 ListTest app = new ListTest();
Initialize JList with array of
Strings, 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. 12.20: MouseDetails.java
2 // Demonstrating mouse clicks and
3 // distinguishing between mouse buttons.
4 import javax.swing.*;
5 import java.awt.*;
6 import java.awt.event.*;
7
8 public class MouseDetails extends JFrame {
9 private String s = "";
10 private int xPos, yPos;
11
12 public MouseDetails()
13 {
14 super( "Mouse clicks and buttons" );
15
16 addMouseListener( new MouseClickHandler() );
17
18 setSize( 350, 150 );
19 show();
20 }
21
22 public void paint( Graphics g )
23 {
24 g.drawString( "Clicked @ [" + 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();
31
32 app.addWindowListener(
33 new WindowAdapter() {
34 public void windowClosing( WindowEvent e )
35 {
36 System.exit( 0 );
37 }
38 }
39 );
40 }
41
42 // inner class to handle mouse events
4343 private class MouseClickHandler extends MouseAdapter {
44 public void mouseClicked( MouseEvent e )
45 {
46 xPos = e.getX();
47 yPos = e.getY();
48
49 String s =
5050 "Clicked " + e.getClickCount() + " time(s)";
51
52 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 OutputProgram Output
5959 setTitle( s ); // set the title bar of the window
60 repaint();
61 }
62 }
63 }
Set the Frame’s title bar.
Learn more aboutLearn more about
Swing compenentsSwing compenents
 http://java.sun.com/docs/books/tutorial/uishttp://java.sun.com/docs/books/tutorial/uis
wing/components/componentlist.htmlwing/components/componentlist.html
Good and bad programming practices with AWTGood and bad programming practices with AWT
 Separate user interface logic from "business logic" or modelSeparate user interface logic from "business logic" or model
 AWT 1.1 "listeners" designed for this purpose; inner classes facilitate it furtherAWT 1.1 "listeners" designed for this purpose; inner classes facilitate it further
 Separation.java example illustrates this approach:Separation.java example illustrates this approach:
 class BusinessLogic knows nothing about UI;class BusinessLogic knows nothing about UI;
 class Separation keeps track of all UI details and talks to BusinessLogicclass Separation keeps track of all UI details and talks to BusinessLogic
through its public interface.through its public interface.
How is this design loosely coupled?How is this design loosely coupled?
How does it support reuse?How does it support reuse?
How does it support legacy code?How does it support legacy code?
 Also note use of inner classes for all "listeners" nested within SeparationAlso note use of inner classes for all "listeners" nested within Separation
 Contrast code of badidea1.java: look at code in actionPerformed:Contrast code of badidea1.java: look at code in actionPerformed:
public void actionPerformed(ActionEvent e)public void actionPerformed(ActionEvent e)
{ Object source = e.getSource();{ Object source = e.getSource();
if (source == b1)if (source == b1)
System.out.println("Button 1 pressed");System.out.println("Button 1 pressed");
else if (source == b2) System.out.println("Button 2 pressed");else if (source == b2) System.out.println("Button 2 pressed");
else System.out.println("Something else");else System.out.println("Something else");
}}
 badidea2.java improves on things by using adapters, but ...badidea2.java improves on things by using adapters, but ...
 Why is the cascadedWhy is the cascaded ifif above a bad idea?above a bad idea?
Eclipse WidgetsEclipse Widgets
 Standard Widget Toolkit (SWT)Standard Widget Toolkit (SWT)

GUI toolkit released in November 2001GUI toolkit released in November 2001

Initially designed for the Eclipse IDEInitially designed for the Eclipse IDE

““Best of both worlds” approach – use nativeBest of both worlds” approach – use native
functionality when available, and Java implementationfunctionality when available, and Java implementation
when unavailablewhen unavailable

Takes on theTakes on the appearanceappearance andand behaviorbehavior of the nativeof the native
platformplatform

The code YOU write will be portable for all theThe code YOU write will be portable for all the
platforms that have SWT implementationsplatforms that have SWT implementations

http://www.eclipse.org/swt/ - SWT home pagehttp://www.eclipse.org/swt/ - SWT home page
GUI BuildersGUI Builders
 Netbeans (Sun)Netbeans (Sun)
 JBuilder (Borland)JBuilder (Borland)
 Eclipse (IBM and others)Eclipse (IBM and others)

Visual EditorVisual Editor
• HelpHelp  Software UpdatesSoftware Updates  Find and Install…Find and Install…
Eclipse Visual EditorEclipse Visual Editor
Thank YouThank You
??????????????

More Related Content

What's hot

Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Appletsamitksaha
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in javaVishnu Suresh
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 

What's hot (20)

Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Applets
AppletsApplets
Applets
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Applets
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
JAVA INTRODUCTION - 1
JAVA INTRODUCTION - 1JAVA INTRODUCTION - 1
JAVA INTRODUCTION - 1
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Java input
Java inputJava input
Java input
 
String in java
String in javaString in java
String in java
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 

Viewers also liked (20)

Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
java swing
java swingjava swing
java swing
 
Java AWT
Java AWTJava AWT
Java AWT
 
Java swing
Java swingJava swing
Java swing
 
Java Swing
Java SwingJava Swing
Java Swing
 
java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)java swing tutorial for beginners(java programming tutorials)
java swing tutorial for beginners(java programming tutorials)
 
Java Swing
Java SwingJava Swing
Java Swing
 
Awt
AwtAwt
Awt
 
Java applets
Java appletsJava applets
Java applets
 
Java applets
Java appletsJava applets
Java applets
 
Java swings
Java swingsJava swings
Java swings
 
java drag and drop and data transfer
java drag and drop and data transferjava drag and drop and data transfer
java drag and drop and data transfer
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
 
java swing programming
java swing programming java swing programming
java swing programming
 
Unit 7 Java
Unit 7 JavaUnit 7 Java
Unit 7 Java
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
 
File operations in c
File operations in cFile operations in c
File operations in c
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
 

Similar to Awt and swing in java

Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892renuka gavli
 
The java swing_tutorial
The java swing_tutorialThe java swing_tutorial
The java swing_tutorialsumitjoshi01
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.pptTabassumMaktum
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web ToolkitsYiguang Hu
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Javasuraj pandey
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window ToolkitRutvaThakkar1
 
108 advancedjava
108 advancedjava108 advancedjava
108 advancedjavaAnil Kumar
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examplesAbdii Rashid
 
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfDeveloping and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfPrabindh Sundareson
 
Advance Java Programming (CM5I) 1.AWT
Advance Java Programming (CM5I) 1.AWTAdvance Java Programming (CM5I) 1.AWT
Advance Java Programming (CM5I) 1.AWTPayal Dungarwal
 

Similar to Awt and swing in java (20)

Gui
GuiGui
Gui
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
The java swing_tutorial
The java swing_tutorialThe java swing_tutorial
The java swing_tutorial
 
The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.ppt
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
GUI JAVA PROG ~hmftj
GUI  JAVA PROG ~hmftjGUI  JAVA PROG ~hmftj
GUI JAVA PROG ~hmftj
 
28 awt
28 awt28 awt
28 awt
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window Toolkit
 
UNIT-2-AJAVA.pdf
UNIT-2-AJAVA.pdfUNIT-2-AJAVA.pdf
UNIT-2-AJAVA.pdf
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
 
swings.pptx
swings.pptxswings.pptx
swings.pptx
 
108 advancedjava
108 advancedjava108 advancedjava
108 advancedjava
 
advanced java programming(java programming tutorials)
 advanced java programming(java programming tutorials) advanced java programming(java programming tutorials)
advanced java programming(java programming tutorials)
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examples
 
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfDeveloping and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
 
Advance Java Programming (CM5I) 1.AWT
Advance Java Programming (CM5I) 1.AWTAdvance Java Programming (CM5I) 1.AWT
Advance Java Programming (CM5I) 1.AWT
 
GUI components in Java
GUI components in JavaGUI components in Java
GUI components in Java
 

More from Shehrevar Davierwala

More from Shehrevar Davierwala (20)

Introduction_Swift
Introduction_SwiftIntroduction_Swift
Introduction_Swift
 
PsudoCode.pptx
PsudoCode.pptxPsudoCode.pptx
PsudoCode.pptx
 
Number System.pptx
Number System.pptxNumber System.pptx
Number System.pptx
 
Java Script (Module 1).pptx
Java Script (Module 1).pptxJava Script (Module 1).pptx
Java Script (Module 1).pptx
 
Website in Clicks Day 2
Website in Clicks Day 2Website in Clicks Day 2
Website in Clicks Day 2
 
Develop Website in Clicks
Develop Website in ClicksDevelop Website in Clicks
Develop Website in Clicks
 
Build Virtual Assistant Using AI
Build Virtual Assistant Using AI Build Virtual Assistant Using AI
Build Virtual Assistant Using AI
 
Build brand reputation using facebook
Build brand reputation using facebookBuild brand reputation using facebook
Build brand reputation using facebook
 
Digital Marketing Session 2
Digital Marketing Session 2Digital Marketing Session 2
Digital Marketing Session 2
 
Learn Digital Marketing : 0 to Hero Day 1
Learn Digital Marketing :  0 to Hero Day 1 Learn Digital Marketing :  0 to Hero Day 1
Learn Digital Marketing : 0 to Hero Day 1
 
Standard template
Standard templateStandard template
Standard template
 
Digital Marketing for Sustainable Business - Afghan Perspective
Digital Marketing for Sustainable Business - Afghan Perspective  Digital Marketing for Sustainable Business - Afghan Perspective
Digital Marketing for Sustainable Business - Afghan Perspective
 
Developing stunning website in clicks - 2
Developing stunning website in clicks - 2Developing stunning website in clicks - 2
Developing stunning website in clicks - 2
 
Developing stunning website in clicks
Developing stunning website in clicksDeveloping stunning website in clicks
Developing stunning website in clicks
 
Google forms for data analysis
Google forms for data analysisGoogle forms for data analysis
Google forms for data analysis
 
Webdesign session1
Webdesign session1Webdesign session1
Webdesign session1
 
Tech talk webtech
Tech talk webtechTech talk webtech
Tech talk webtech
 
Tech talk php_cms
Tech talk php_cmsTech talk php_cms
Tech talk php_cms
 
Ph pbasics
Ph pbasicsPh pbasics
Ph pbasics
 
Php mysql
Php mysqlPhp mysql
Php mysql
 

Recently uploaded

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Awt and swing in java

  • 1. AWT- Abstract Window Tool KitAWT- Abstract Window Tool Kit SwingSwing Presentation By: Shehrevar Davierwala http://sites.google.com/site/techwizardin www.authorstream.com/shehrevard
  • 2. AWT and SwingAWT and Swing  Most GUI class libraries in C++ are platform specificMost GUI class libraries in C++ are platform specific  Different hardware capabilitiesDifferent hardware capabilities  Subtle differences between the "look-and-feel" of variousSubtle differences between the "look-and-feel" of various Windowing operating systemsWindowing operating systems  Abstract Window Toolkit (AWT) is cross-platformAbstract Window Toolkit (AWT) is cross-platform  Swing can observe various OS look-and-feel conventionsSwing can observe various OS look-and-feel conventions
  • 3. Common functionality/specific implementation approachCommon functionality/specific implementation approach Toolkit -------------------------------------------------- AWTToolkit -------------------------------------------------- AWT -----------|-----------------------|------------ Button List JVMButton List JVM | | Native GUI| | Native GUI Button Peer List Peer (Windows, Mac, X)Button Peer List Peer (Windows, Mac, X)  AWT GUI classes are platform-independent elementsAWT GUI classes are platform-independent elements  Each AWT platform-specific toolkit comes withEach AWT platform-specific toolkit comes with peerpeer classclass implementing platform-specific behavior of its AWT classimplementing platform-specific behavior of its AWT class  Combining platform-independent AWT class withCombining platform-independent AWT class with platform-specific peer class transforms generic, abstract windowsplatform-specific peer class transforms generic, abstract windows behavior into specific, particular behaviorbehavior into specific, particular behavior
  • 4. Peer classes at run-timePeer classes at run-time class TestPeer {class TestPeer { TestPeer() {TestPeer() { Frame myFrame = new Frame("my Frame"); //create window FrameFrame myFrame = new Frame("my Frame"); //create window Frame Button myButton = new Button("my Button"); //create myButtonButton myButton = new Button("my Button"); //create myButton myFrame.add("Center",myButton); //put myButton in myFramemyFrame.add("Center",myButton); //put myButton in myFrame myFrame.setVisible(true); //button appears in window on screenmyFrame.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 worksComponentPeer buttonPeer = myButton.getPeer(); //now works }} }}  TestPeer first constructs a frame, then adds a button on the frameTestPeer first constructs a frame, then adds a button on the frame  setVisible method creates peer objects on platformsetVisible method creates peer objects on platform  Last line now accesses myButton’s peer objectLast line now accesses myButton’s peer object  Peer classes are usually hidden from developers. Why?Peer classes are usually hidden from developers. Why?  In fact, in newer versions of JDK, getPeer() method is "deprecated"In fact, in newer versions of JDK, getPeer() method is "deprecated"  Peer classes strongly discouraged for code maintenance purposesPeer 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.
  • 5. JDK 1.0 (circa 1996)JDK 1.0 (circa 1996)  JDK 1.0 went a long way to implementingJDK 1.0 went a long way to implementing platform-independent GUI libraryplatform-independent GUI library  Bruce Eckel: it "produced a GUI that looksBruce Eckel: it "produced a GUI that looks equally mediocre on all systems."equally mediocre on all systems."  Just 4 fontsJust 4 fonts  Couldn’t access GUI of native OSCouldn’t access GUI of native OS  Didn’t separate model and UI code cleanlyDidn’t separate model and UI code cleanly
  • 6. JDK 1.1 (circa 1998)JDK 1.1 (circa 1998)  JDK 1.1 makes AWT more robust and extensibleJDK 1.1 makes AWT more robust and extensible  Delegation-based event model separates userDelegation-based event model separates user interface from problem domaininterface from problem domain  Avoids cascaded if statements testing for object typeAvoids cascaded if statements testing for object type required by first AWTrequired by first AWT  Designates "listeners" of events triggered by problemDesignates "listeners" of events triggered by problem domain objectsdomain objects  Listeners implement the Observer design patternListeners implement the Observer design pattern  Other enhancements: button tool tips, cut/pasteOther enhancements: button tool tips, cut/paste to the clipboard, popup menus, printing, etc.to the clipboard, popup menus, printing, etc.  Adds supports for JavaBeansAdds supports for JavaBeans
  • 7. JDK 1.2 (Swing)JDK 1.2 (Swing)  JDK 1.2 adds Java Foundation ClassesJDK 1.2 adds Java Foundation Classes  Swing is the GUI library for JDK 1.2Swing is the GUI library for JDK 1.2  Much richer class library plus better integrationMuch richer class library plus better integration with look and feel of GUI of OSwith look and feel of GUI of OS  Eckel: "The ‘revision 3’ rule of software industryEckel: "The ‘revision 3’ rule of software industry (a product isn’t good until revision 3) seems to(a product isn’t good until revision 3) seems to hold true with programming languages as well."hold true with programming languages as well."
  • 8. Graphical ComponentsGraphical Componentsbutton menus title bar menu bar combo box scroll bars
  • 9. AWT class hierarchyAWT class hierarchy Checkbox, Choice, Label, List, Scrollbar,ScrollPane, TextArea, TextField
  • 10. Component and ContainerComponent and Container  ComponentComponent contributes several public methods to all its subclasses:contributes several public methods to all its subclasses: public void setSize(int width, int height);public void setSize(int width, int height); //set size in pixels//set size in pixels public void setBackground(Color c);public void setBackground(Color c); //see class Color for colors//see class Color for colors public void setVisible(boolean b);public void setVisible(boolean b); //Display on screen (creates peer)//Display on screen (creates peer)  ContainerContainer is an abstract class:is an abstract class:  It cannot be instantiated; subclasses must implement some methodsIt cannot be instantiated; subclasses must implement some methods  ContainerContainer does implement some useful methods, includingdoes implement some useful methods, including:: public Component add(Component comp);public Component add(Component comp); //put a Component in a Container//put a Component in a Container public setLayout(LayoutManager mgr);public setLayout(LayoutManager mgr); //lay out components in some pattern//lay out components in some pattern
  • 11. Window and Frame classesWindow and Frame classes  AA WindowWindow is a top-level window with no borders and no menubaris a top-level window with no borders and no menubar  It can generate aIt can generate a WindowOpenedWindowOpened or aor a WindowClosedWindowClosed event,event, to which ato which a WindowListenerWindowListener oror WindowAdapterWindowAdapter can respondcan respond  AA FrameFrame is a top-level window with a title and a borderis a top-level window with a title and a border  Because it has more features, it can generate more events:Because it has more features, it can generate more events: WindowOpened, WindowClosing, WindowClosed,WindowOpened, WindowClosing, WindowClosed, WindowIconified, WindowDeiconified,WindowIconified, WindowDeiconified, WindowActivated, WindowDeactivatedWindowActivated, WindowDeactivated  Respond to these events with aRespond to these events with a WindowListenerWindowListener  Once a subclass of Container has been constructed, it canOnce a subclass of Container has been constructed, it can addadd (attach) any AWT component within it, such as a Button, Label,(attach) any AWT component within it, such as a Button, Label, TextField, or another Frame or PanelTextField, or another Frame or Panel
  • 12. A simple exampleA simple example //Demonstrates construction of a Container and a Button//Demonstrates construction of a Container and a Button import java.awt.*;import java.awt.*; class Gui extends Frameclass Gui extends Frame {{ public Gui(String s)public Gui(String s) //constructor//constructor { super(s);{ super(s); //construct Frame part of Gui//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 Gui class Ex_1class Ex_1 //Creates an instance of class Gui//Creates an instance of class Gui { public static void main(String[] args){ 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} //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?
  • 13. Responding to eventsResponding to events //Program to demonstrate action listeners and event handlers//Program to demonstrate action listeners and event handlers import java.awt.*;import java.awt.*; import java.awt.event.*;import java.awt.event.*; class Gui extends Frame implements ActionListener, WindowListenerclass Gui extends Frame implements ActionListener, WindowListener { public Gui(String s) //constructor{ 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 WindowaddWindowListener(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 presspushButton.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 nothingpublic 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. When the ActionEvent labeled "press me""press me" occurs, print (ring) the bell.
  • 14. Responding to events, continuedResponding to events, continued  Uses event delegation model of JDK 1.1Uses event delegation model of JDK 1.1  When an event occurs, it generates anWhen an event occurs, it generates an ActionEventActionEvent objectobject  ActionListenerActionListener interface listens for a particularinterface listens for a particular ActionEventActionEvent  Responds in itsResponds in its actionPerformedactionPerformed methodmethod  WindowListenerWindowListener interface observes events triggered byinterface observes events triggered by WindowWindow object, such as closing it, and responds inobject, such as closing it, and responds in corresponding methodscorresponding methods  Program now has a live Button:Program now has a live Button: actionPerformedactionPerformed methodmethod rings a bellrings a bell  Also a live close window button, which performsAlso a live close window button, which performs System.exit(0)System.exit(0)  Most Components in the AWT have corresponding ListenersMost Components in the AWT have corresponding Listeners
  • 15. Adapter ClassesAdapter Classes  Time consuming to define all interface methodsTime consuming to define all interface methods  WindowListenerWindowListener has seven methodshas 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 iAdapter class implements an interfacemplements 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 asoverriding methods for events you care about, such as windowClosingwindowClosing..  Has "is a" relationship with interfaceHas "is a" relationship with interface • WindowAdapterWindowAdapter is ais a WindowListenerWindowListener • MouseAdapterMouseAdapter is ais a MouseListenerMouseListener
  • 16. Layout managersLayout managers  Sketchpad uses hard-coded layout, which depends on a 800x600 screenSketchpad uses hard-coded layout, which depends on a 800x600 screenJDK provides a set of genericJDK provides a set of generic layout managerlayout manager classesclasses • Arrange Component objects within a Container object in predictable waysArrange Component objects within a Container object in predictable ways FlowLayout (the default) add components one after another in rows:FlowLayout (the default) add components one after another in rows: setLayout(new FlowLayout(FlowLayout.LEFT,10,10);setLayout(new FlowLayout(FlowLayout.LEFT,10,10); for (int counter=1; counter <= 6; counter++)for (int counter=1; counter <= 6; counter++) add(new Button(String.valueOf(counter)));add(new Button(String.valueOf(counter))); 1 2 31 2 3 4 5 64 5 6 GridLayout places components in cells of a grid:GridLayout places components in cells of a grid: setLayout(new GridLayout(3,2,5,5);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++)for (int counter=1; counter <= 6; counter++) add(new Button(String.valueOf(counter)));add(new Button(String.valueOf(counter))); 1 21 2 3 43 4 5 65 6 BorderLayout arranges components using along four sidesBorderLayout arranges components using along four sides (North, South, East West) and Center positions(North, South, East West) and Center positions
  • 17. Swing overviewSwing overview  Defined in packageDefined in package javax.swingjavax.swing  Original GUI components from AWT inOriginal GUI components from AWT in java.awtjava.awt  HeavyweightHeavyweight components - rely on local platform'scomponents - rely on local platform's windowing system for look and feelwindowing system for look and feel  Swing components areSwing components are lightweightlightweight  Not weighed down by GUI capabilities of platformNot weighed down by GUI capabilities of platform  More portable than heavyweight componentsMore portable than heavyweight components  Swing components allow programmer to specify look and feelSwing components allow programmer to specify look and feel  Can change depending on platformCan change depending on platform  Can be same across all platformsCan be same across all platforms
  • 18. Swing component inheritance hierarchySwing 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
  • 19. Jcomponent featuresJcomponent features  Pluggable look and feelPluggable look and feel  Can look like different platforms, at run-timeCan look like different platforms, at run-time  Shortcut keys (mnemonics)Shortcut keys (mnemonics)  Direct access to components through keyboardDirect access to components through keyboard  Common event handlingCommon event handling  If several components perform same actionsIf several components perform same actions  Tool tipsTool tips  Describe component when mouse rolls over itDescribe component when mouse rolls over it
  • 20. MenusMenus Menu BarMenu Bar  JMenuBar()JMenuBar()  add( JMenu )add( JMenu ) MenuMenu  JMenu( String )JMenu( String )  add( JMenuItem )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 )
  • 21. JLabelJLabel  LabelsLabels  Provide text instructions on a GUIProvide text instructions on a GUI  Read-only textRead-only text  Programs rarely change a label's contentsPrograms rarely change a label's contents  ClassClass JLabelJLabel (subclass of(subclass of JComponentJComponent))  MethodsMethods  Can declare label text in constructorCan declare label text in constructor  myLabel.setToolTipText( "Text" )myLabel.setToolTipText( "Text" ) • DisplaysDisplays "Text""Text" in a tool tip when mouse over labelin a tool tip when mouse over label  myLabel.setText( "Text" )myLabel.setText( "Text" )  myLabel.getText()myLabel.getText()
  • 22. JLabelJLabel  IconIcon  Object that implements interfaceObject that implements interface IconIcon  One class isOne class is ImageIconImageIcon ((.gif.gif andand .jpeg.jpeg images)images) • Assumed same directory as programAssumed same directory as program  Display an icon withDisplay an icon with JLabelJLabel’s’s setIconsetIcon methodmethod • 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 );
  • 23. 1 // Fig. 12.4: LabelTest.java 2 // Demonstrating the JLabel class. 3 import javax.swing.*; 4 import java.awt.*; 5 import java.awt.event.*; 6 7 public class LabelTest extends JFrame { 8 private JLabel label1, label2, label3; 9 10 public LabelTest() 11 { 12 super( "Testing JLabel" ); 13 1414 Container c = getContentPane(); 15 c.setLayout( new FlowLayout() ); 16 17 // JLabel constructor with a string argument 1818 label1 = new JLabel( "Label with text" ); 1919 label1.setToolTipText( "This is label1" ); 20 c.add( label1 ); 21 22 // JLabel constructor with string, Icon and 23 // alignment arguments 2424 Icon bug = new ImageIcon( "bug1.gif" ); 2525 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.
  • 24. JButtonJButton  Methods of classMethods of class JButtonJButton  ConstructorsConstructors JButton myButton = new JButton( "Label" );JButton myButton = new JButton( "Label" ); JButton myButton = new JButton( "Label", myIcon );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  ClassClass ActionEvent getActionCommandActionEvent 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 );
  • 25. JCheckBoxJCheckBox  WhenWhen JCheckBoxJCheckBox changeschanges  ItemEventItemEvent generatedgenerated • Handled by anHandled by an ItemListenerItemListener, which must define, which must define itemStateChangeditemStateChanged  Register handlers with withRegister handlers with with addItemListeneraddItemListener  ClassClass ItemEventItemEvent  getStateChangegetStateChange • ReturnsReturns ItemEvent.SELECTEDItemEvent.SELECTED oror ItemEvent.DESELECTEDItemEvent.DESELECTED private class CheckBoxHandler implements ItemListener { public void itemStateChanged( ItemEvent e )
  • 26. 1.1. importimport 1.1 Declarations1.1 Declarations 1 // Fig. 12.12: CheckBoxTest.java 2 // Creating Checkbox buttons. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class CheckBoxTest extends JFrame { 8 private JTextField t; 9 private JCheckBox bold, italic; 10 11 public CheckBoxTest() 12 { 13 super( "JCheckBox Test" ); 14 15 Container c = getContentPane(); 16 c.setLayout(new FlowLayout()); 17 18 t = new JTextField( "Watch the font style change", 20 ); 19 t.setFont( new Font( "TimesRoman", Font.PLAIN, 14 ) ); 20 c.add( t ); 21 22 // create checkbox objects 2323 bold = new JCheckBox( "Bold" ); 24 c.add( bold ); 25 26 italic = new JCheckBox( "Italic" ); 27 c.add( italic ); 28 29 CheckBoxHandler handler = new CheckBoxHandler(); 30 bold.addItemListener( handler ); Create JCheckBoxes
  • 27. 31 italic.addItemListener( handler ); 32 33 addWindowListener( 34 new WindowAdapter() { 35 public void windowClosing( WindowEvent e ) 36 { 37 System.exit( 0 ); 38 } 39 } 40 ); 41 42 setSize( 275, 100 ); 43 show(); 44 } 45 46 public static void main( String args[] ) 47 { 48 new CheckBoxTest(); 49 } 50 5151 private class CheckBoxHandler implements ItemListener { 52 private int valBold = Font.PLAIN; 53 private int valItalic = Font.PLAIN; 54 55 public void itemStateChanged( ItemEvent e ) 56 { 57 if ( e.getSource() == bold ) 5858 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
  • 28. JRadioButtonJRadioButton  Radio buttonsRadio buttons  Have two states: selected and deselectedHave two states: selected and deselected  Normally appear as a groupNormally 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 optionsMutually exclusive options  ButtonGroupButtonGroup - maintains logical relationship between- maintains logical relationship between radio buttonsradio buttons  ClassClass JRadioButtonJRadioButton  ConstructorConstructor • JRadioButton( "Label", selected )JRadioButton( "Label", selected ) • If selectedIf selected truetrue,, JRadioButtonJRadioButton initially selectedinitially selected
  • 29. 1.1. importimport 1.1 Declarations1.1 Declarations 1 // Fig. 12.12: RadioButtonTest.java 2 // Creating radio buttons using ButtonGroup and JRadioButton. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public 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; 13 14 public RadioButtonTest() 15 { 16 super( "RadioButton Test" ); 17 18 Container c = getContentPane(); 19 c.setLayout( new FlowLayout() ); 20 21 t = new JTextField( "Watch the font style change", 25 ); 22 c.add( t ); 23 24 // 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.
  • 30. 31 boldItalic = new JRadioButton( "Bold/Italic", false ); 32 c.add( boldItalic ); 33 34 // register events 35 RadioButtonHandler handler = new RadioButtonHandler(); 36 plain.addItemListener( handler ); 37 bold.addItemListener( handler ); 38 italic.addItemListener( handler ); 39 boldItalic.addItemListener( handler ); 40 41 // create logical relationship between JRadioButtons 4242 radioGroup = new ButtonGroup(); 4343 radioGroup.add( plain ); 44 radioGroup.add( bold ); 45 radioGroup.add( italic ); 46 radioGroup.add( boldItalic ); 47 48 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 ); 54 55 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
  • 31.
  • 32. JListJList  ListList  Displays series of itemsDisplays series of items  may select one or more itemsmay select one or more items  ClassClass JListJList  ConstructorConstructor JList( arrayOfNames )JList( arrayOfNames ) • Takes array ofTakes array of ObjectsObjects ((StringStrings) to display in lists) to display in list  setVisibleRowCount( n )setVisibleRowCount( n ) • DisplaysDisplays nn items at a timeitems at a time • Does not provide automatic scrollingDoes not provide automatic scrolling
  • 33. 30 // create a list with the items in the colorNames array 3131 colorList = new JList( colorNames ); 32 colorList.setVisibleRowCount( 5 ); 33 34 // do not allow multiple selections 3535 colorList.setSelectionMode( 36 ListSelectionModel.SINGLE_SELECTION ); 37 38 // add a JScrollPane containing the JList 39 // to the content pane 4040 c.add( new JScrollPane( colorList ) ); 41 42 // set up event handler 43 colorList.addListSelectionListener( 44 new ListSelectionListener() { 45 public void valueChanged( ListSelectionEvent e ) 46 { 4747 c.setBackground( 48 colors[ colorList.getSelectedIndex() ] ); 49 } 50 } 51 ); 52 53 setSize( 350, 150 ); 54 show(); 55 } 56 57 public static void main( String args[] ) 58 { 59 ListTest app = new ListTest(); Initialize JList with array of Strings, 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).
  • 34. 1 // Fig. 12.20: MouseDetails.java 2 // Demonstrating mouse clicks and 3 // distinguishing between mouse buttons. 4 import javax.swing.*; 5 import java.awt.*; 6 import java.awt.event.*; 7 8 public class MouseDetails extends JFrame { 9 private String s = ""; 10 private int xPos, yPos; 11 12 public MouseDetails() 13 { 14 super( "Mouse clicks and buttons" ); 15 16 addMouseListener( new MouseClickHandler() ); 17 18 setSize( 350, 150 ); 19 show(); 20 } 21 22 public void paint( Graphics g ) 23 { 24 g.drawString( "Clicked @ [" + xPos + ", " + yPos + "]", 25 xPos, yPos ); 26 } 27 Another example, illustrating mouse events in AWT and Swing Add a listener for a mouse click.
  • 35. 28 public static void main( String args[] ) 29 { 30 MouseDetails app = new MouseDetails(); 31 32 app.addWindowListener( 33 new WindowAdapter() { 34 public void windowClosing( WindowEvent e ) 35 { 36 System.exit( 0 ); 37 } 38 } 39 ); 40 } 41 42 // inner class to handle mouse events 4343 private class MouseClickHandler extends MouseAdapter { 44 public void mouseClicked( MouseEvent e ) 45 { 46 xPos = e.getX(); 47 yPos = e.getY(); 48 49 String s = 5050 "Clicked " + e.getClickCount() + " time(s)"; 51 52 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.
  • 36. Program OutputProgram Output 5959 setTitle( s ); // set the title bar of the window 60 repaint(); 61 } 62 } 63 } Set the Frame’s title bar.
  • 37. Learn more aboutLearn more about Swing compenentsSwing compenents  http://java.sun.com/docs/books/tutorial/uishttp://java.sun.com/docs/books/tutorial/uis wing/components/componentlist.htmlwing/components/componentlist.html
  • 38. Good and bad programming practices with AWTGood and bad programming practices with AWT  Separate user interface logic from "business logic" or modelSeparate user interface logic from "business logic" or model  AWT 1.1 "listeners" designed for this purpose; inner classes facilitate it furtherAWT 1.1 "listeners" designed for this purpose; inner classes facilitate it further  Separation.java example illustrates this approach:Separation.java example illustrates this approach:  class BusinessLogic knows nothing about UI;class BusinessLogic knows nothing about UI;  class Separation keeps track of all UI details and talks to BusinessLogicclass Separation keeps track of all UI details and talks to BusinessLogic through its public interface.through its public interface. How is this design loosely coupled?How is this design loosely coupled? How does it support reuse?How does it support reuse? How does it support legacy code?How does it support legacy code?  Also note use of inner classes for all "listeners" nested within SeparationAlso note use of inner classes for all "listeners" nested within Separation  Contrast code of badidea1.java: look at code in actionPerformed:Contrast code of badidea1.java: look at code in actionPerformed: public void actionPerformed(ActionEvent e)public void actionPerformed(ActionEvent e) { Object source = e.getSource();{ Object source = e.getSource(); if (source == b1)if (source == b1) System.out.println("Button 1 pressed");System.out.println("Button 1 pressed"); else if (source == b2) System.out.println("Button 2 pressed");else if (source == b2) System.out.println("Button 2 pressed"); else System.out.println("Something else");else System.out.println("Something else"); }}  badidea2.java improves on things by using adapters, but ...badidea2.java improves on things by using adapters, but ...  Why is the cascadedWhy is the cascaded ifif above a bad idea?above a bad idea?
  • 39. Eclipse WidgetsEclipse Widgets  Standard Widget Toolkit (SWT)Standard Widget Toolkit (SWT)  GUI toolkit released in November 2001GUI toolkit released in November 2001  Initially designed for the Eclipse IDEInitially designed for the Eclipse IDE  ““Best of both worlds” approach – use nativeBest of both worlds” approach – use native functionality when available, and Java implementationfunctionality when available, and Java implementation when unavailablewhen unavailable  Takes on theTakes on the appearanceappearance andand behaviorbehavior of the nativeof the native platformplatform  The code YOU write will be portable for all theThe code YOU write will be portable for all the platforms that have SWT implementationsplatforms that have SWT implementations  http://www.eclipse.org/swt/ - SWT home pagehttp://www.eclipse.org/swt/ - SWT home page
  • 40. GUI BuildersGUI Builders  Netbeans (Sun)Netbeans (Sun)  JBuilder (Borland)JBuilder (Borland)  Eclipse (IBM and others)Eclipse (IBM and others)  Visual EditorVisual Editor • HelpHelp  Software UpdatesSoftware Updates  Find and Install…Find and Install…
  • 42.