Swing Introduction Unit-4-5
Swing Introduction Unit-4-5
Swing In Java
AWT SWING
• Platform Dependent • Platform Independent
• Does not follow MVC • Follows MVC
• Lesser Components • More powerful components
• Does not support pluggable • Supports pluggable look and
look and feel feel
• Heavyweight • Lightweight
Java Swing Class Hierarchy
Swing inheritance hierarchy
• Component (AWT)
– Window import java.awt.*;
import javax.swing.*;
• Frame
• JFrame (Swing)
• JDialog
– Container
• JComponent (Swing)
• JButton JColorChooser JFileChooser
• JComboBox JLabel JList
• JMenuBar JOptionPane JPanel
• JPopupMenu JProgressBar JScrollbar
• JScrollPane JSlider JSpinner
• JSplitPane JTabbedPane JTable
• JToolbar JTree JTextArea
• JTextField ...
Component properties
– Each has a get (or is) accessor and a set modifier method.
– examples: getColor, setFont, setEnabled, isVisible
name type description
background Color background color behind component
border Border border line around component
enabled boolean whether it can be interacted with
focusable boolean whether key text can be typed on it
font Font font used for text in component
foreground Color foreground color of component
height, width int component's current size in pixels
visible boolean whether component can be seen
tooltip text String text shown when hovering mouse
size, minimum / Dimension various sizes, size limits, or desired
maximum / preferred size sizes that the component may take
JFrame
• public JFrame()
public JFrame(String title)
Creates a frame with an optional title.
public BorderLayout()
myFrame.setLayout(new FlowLayout());
myFrame.add(new JButton("Button 1"));
frame.getContentPane().add(BorderLayout.SOUTH,
panel);
frame.getContentPane().add(BorderLayout.NORTH, tf);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(true);
}
}
output
Event Listeners
Graphical events
• event: An object that represents a user's interaction with a GUI
component; can be "handled" to create interactive components.
import java.awt.event.*;
• EventObject • EventListener
– AWTEvent (AWT) – AWTEventListener
• ActionEvent – ActionListener
• TextEvent – TextListener
• ComponentEvent – ComponentListener
– FocusEvent – FocusListener
– WindowEvent – WindowListener
– InputEvent
• KeyEvent – KeyListener
• MouseEvent – MouseListener
Action events
• action event: An action that has occurred on a GUI component.
The most common, general event type in Swing. Caused by:
button or menu clicks,
check box checking / unchecking,
pressing Enter in a text field, ...
• Usefulness:
Nested classes are hidden from other classes (encapsulated).
Nested objects can access/modify the fields of their outer object.
Only the outer class can see the nested class or make objects of it.
Each nested object is associated with the outer object that
created it, so it can access/modify that outer object's
methods/fields.
• If necessary, can refer to outer object as OuterClassName.this
Static inner classes
// enclosing outer class
public class name {
...
public MyGUI() {
...
stutter.addActionListener(new StutterListener());
}
...
Event-Driven Programming
61
Window Manager
• Controls placement and appearance of windows
(but not the window contents)
– Open, close, minimize, maximize, move, resize
– Start apps, list and switch between running apps
– Window decorators, desktop background with icons
• Often built into windowing system
• Implemented using a widget toolkit
62
Introduction to Java Swing
63
Swing Design Principles
• GUI is built as containment hierarchy of widgets
(i.e. the parent-child nesting relation between
them)
• Event objects and event listeners
– Event object: is created when event occurs (e.g. click),
contains additional info (e.g. mouse coordinates)
– Event listener: object implementing an interface with
an event handler method that gets an event object as
argument
• Separation of Model and View:
– Model: the data that is presented by a widget
– View: the actual presentation on the screen
64
Partial AWT and Swing
Class Hierarchy
java.lang.Object
java.awt.* javax.swing.* 65
The Initial Swing GUI
Containment Hierarchy
a 3D model
enables menus
Frame / Dialog / Applet to pop up above
the content pane
Root Pane
Layered Pane
File Edit
Undo
Redo
Cut
rootPane:
JRootPane
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Toolkit.getDefaultToolkit().beep();
}
}
68
Containment Hierarchy
…
of a Menu
public class MenuExample {
public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE); File Edit
JMenu fileMenu = new JMenu("File");
fileMenu.add(new JMenuItem("New")); New
fileMenu.add(new JMenuItem("Open")); Open
fileMenu.add(new JMenuItem("Close")); Close
JMenu editMenu = new JMenu("Edit");
editMenu.add(new JMenuItem("Undo")); File Edit
editMenu.add(new JMenuItem("Redo"));
editMenu.add(new JMenuItem("Cut")); Undo
Redo
JMenuBar menubar = new JMenuBar();
Cut
menubar.add(fileMenu);
menubar.add(editMenu);
frame.setJMenuBar(menubar);
frame.setVisible(true); 69
} }
Handling Menu Events
...
public class MenuExample {
static JFrame frame;
public static void main(String[] args) {
...
JMenuItem item = new JMenuItem("Close");
item.addActionListener(new MenuActionListener());
fileMenu.add(item);
...
} }
...
public class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(MenuExample.frame,
"Got an ActionEvent at " + new Date(e.getWhen())
+ " from " + e.getSource().getClass());
} } 70
Defining Event Listeners with Anonynous
Classes
...
public class MenuExample {
public static void main(String[] args) {
final JFrame frame = new JFrame("My Frame");
...
JMenuItem item = new JMenuItem("Close");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showOptionDialog(frame,...
}
});
...
} }
72
Events, Listeners, Adapters and
Handler Methods
Event Listener / Handler Methods
Adapter
ActionEvent ActionListener actionPerformed
AdjustmentEvent AdjustmentListener adjustmentValueChanged
MouseEvent MouseListener mouseClicked
MouseAdapter mouseEntered
mouseExited
mousePressed
mouseReleased
KeyEvent KeyListener keyPressed
KeyAdapter keyReleased
keyTyped
ComponentEvent ComponentListener componentShown
ComponentAdapter componentHidden
componentMoved
componentResized
Adapter classes with empty methods for Listener interfaces with >1 methods
73
Summary
• Desktop environments consist of:
– Windowing System: handles input/output
– Widget Toolkit:
draws widgets and dispatches their events
– Window Manager: takes care of windows
• Swing is a widget toolkit for Java
– GUI as containment hierarchy of widgets
– Event objects and event listeners
References:
http://java.sun.com/docs/books/tutorial/uiswing/
http://www.javabeginner.com/java-swing-tutorial.htm
74