Datenbank-Praktikum - Universität zu Lübeck

snottybugbearSoftware and s/w Development

Nov 3, 2013 (3 years and 9 months ago)


Ho Ngoc Duc 1
Universität zu Lübeck
Sommersemester 2006
Lecture: Swing
Ho Ngoc Duc
Learning objectives
 GUI applications
 Font, Color, Image
 Running Applets as applications
 Swing Components
 Text input
 Scrolling
 Reference:
 Core Java, Ch. 7 & 9
 TIJ, Ch. 14
 Tutorial, Trail: Creating a GUI with JFC/Swing
Ho Ngoc Duc
Class javax.swing.JFrame
 Each GUI application must have a container
that holds everything else
 Top-level container (not contained in another
 In Swing: JFrame
 Method getContentPane() gives the JFrame's
content pane where other components can
be added to
Ho Ngoc Duc
Creating a GUI application
import javax.swing.*;
public class HelloSwing {
public static void main(String[] args) {
JFrame f = new JFrame("Hello Swing");
f.setSize(300, 100);
Steps to create a simple GUI application:
1.Import package javax.swing
2.Create a JFrame
3.Set the frame size
4.Define operation when frame closed
5.Make frame visible
Ho Ngoc Duc
Frame positioning
 setTitle(String) changes the text of title bar
 setResizeable(boolean)
 To set size and position
 setSize(width, height)
 setLocation(x, y)
 setBounds(x, y, width, height)
 pack() compute size based on preferred size of components
• JFrame inherits all methods of ancestors
• Location of a JFrame specified relative
to the whole screen (not to another
Ho Ngoc Duc
The JLabel Class
 Most basic component
 Used to display a single line of text
 The text cannot be edited by the user, but it
can be changed by program
 Constructors:
JLabel msg = new JLabel("Hello World!");
JLabel msg = new JLabel("Hello World!", JLabel.CENTER);
 Change displayed text: setText()
msg.setText("Goodby World!");
Ho Ngoc Duc
The JButton Class
 An object of class JButton is a push button
 Constructors:
JButton stopGoButton = new JButton("Go")
given String becomes the text displayed on the button
 Simple but useful methods:
 setText(String): change the displayed text
 setEnabled(boolean): enable/disable button
 The button will change its appearance
Ho Ngoc Duc
 Input a single line of text
 Constructors:
 JTextField()
 JTextField(String): with a text
 JTextField(String, int): with text and number of
 Methods: getText(), setText(String)
Ho Ngoc Duc
Tooltips and HTML
 JComponent has a method setToolTipText()
 When move mouse over component: tooltip text shows short info
about it
JButton b = new JButton("Compute");
b.setToolTipText("Click to compute the product");
 The tooltip text can be formatted with HTML
 Start text with <html>, then HTML formatting
 No need for closing tag </html>
 Many components (JButton, JLabel…) can display a HTML-
formatted text
JLabel lb = new JLabel("<html><h2>Big text</h2>");
 JLabel and various buttons (JButton, JCheckBox,
JRadioButton…) can contain an Icon (javax.swing.Icon)
 Usually: javax.swing.ImageIcon
Ho Ngoc Duc
HTML label example
public class FrameDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Hello Swing");
Container c = f.getContentPane();
JButton top, left, right;
c.add(top = new JButton("Top button"), BorderLayout.NORTH);
top.setToolTipText("A simple button that does nothing");
JLabel lb = new JLabel("A label with an Icon", new ImageIcon("me.jpg"), JLabel.CENTER);
lb.setFont(new Font("Arial", Font.BOLD, 24));
lb.setToolTipText("The text of the label uses font: "+lb.getFont());
c.add(lb, BorderLayout.CENTER);
String txt1 = "<html><center><h3>This</h3> <h2>is a fancy button</h2> <u>with HTML</u>";
c.add(left = new JButton(txt1), BorderLayout.WEST);
left.setToolTipText("A button with HTML text");
c.add(right = new JButton("Right button"), BorderLayout.EAST);
String txt2 = "<html>This button has a <b><i>red</i></b> text";
f.pack(); // What happnes if you call f.setSize(200, 200); ?
Ho Ngoc Duc
Fancy buttons and labels
 Font and color of the text
displayed on a component
can be set with setFont(),
setBackground() and
 When pack() called:
calculate space needed to
accommodate all
 getPreferredSize()
already implemented for
standard components
 If you write your own
components: should
override it
Ho Ngoc Duc
Introduction to Layout
 The components in a container must be "laid
out", i.e., setting their sizes and positions
 Possible to program the layout yourself
 but normally layout is done by a layout manager
 Layout manager:
 object associated with a container
 implements some policy for laying out the
components in that container
 Different types of layout manager implement
different policies
Ho Ngoc Duc
 Every JPanel comes automatically with a
layout manager
 This default layout manager simply lines up
the components that are added to it in a row
 If next component does not fit: next row
 Resizing the JPanel: components rearranged
 Components have their "natural" size
 If we want to use a certain layout manager for
a container: call setLayout()
Ho Ngoc Duc
 If you want a big component (or group of
components) in the middle, and 1, 2, 3 or 4 (small)
components around it: BorderLayout
 It is the default layout manager for an applet's
content pane
 Add components with add(int, Component), where
the 1st argument one of the constants
 BorderLayout.NORTH, BorderLayout.SOUTH,
BorderLayout.EAST, BorderLayout.WEST, and
BorderLayout. CENTER
 Adding without specifying an area: CENTER
Ho Ngoc Duc
 A GridLayout allows you to build a table of
 As you add them, they are placed left-to-right
and top-to-bottom in the grid
 In the constructor you specify the number of
rows and columns that you need
 one of these numbers may be 0
 cells have the same size
 stretched / compressed to fit in container
Ho Ngoc Duc
Absolute positioning
 It is also possible to set the absolute position
of the graphical components
 Set a null layout manager for your Container:
 Call setBounds() for each component, passing a
bounding rectangle in pixel coordinates
 Some GUI builders use this approach
 usually not the best way to generate code
Ho Ngoc Duc
Event handling
 You can click buttons. They seems to change
the appearance, but nothing else happens
 To make things happen: capture the event
that a button has been clicked, and write
code to carry out the reaction.
 Any Swing component (like JButton) can
report any or all the things that happen to it
 You express your interest (or not) by writing
event handlers (or not)
Ho Ngoc Duc
The Swing Event Model
 Swing components can "fire" different kinds of
 Each type of event is represented by a distinct class
 We can write listeners (implementors of associated
listener interface) and register them to certain
 When an event is fired, it is received by any listener that
has registered to respond to the event,
 Many event/listener types
 ActionEvent / ActionListener
 MouseEvent / MouseListener, MouseMotionListener
 KeyEvent / KeyListener
Ho Ngoc Duc
Buttons with ActionListener
import java.awt.event.*;
import javax.swing.*;
public class ActionDemo extends JPanel {
private JButton b1 = new JButton("Button 1");
private JButton b2 = new JButton("Button 2");
public void init() {
setLayout(new java.awt.FlowLayout());
b1.addActionListener(new AL());
class AL implements ActionListener {
public void actionPerformed(ActionEvent e) {
public static void main(String[] args) {
// …
Ho Ngoc Duc
Using images
 In Java 1.4, reading an image is easy with
String filename = "...";
Image image = File(filename));
 The Graphics class has drawImage() method
 Draw image on panel:
g.drawImage(image, x, y, null);
 Need to set panel's preferred size and put it
in a JScrollPane
 Finally, display panel in a frame
Ho Ngoc Duc
Image example
import java.awt.*;
import javax.swing.*;
public class ImageDemo extends JPanel {
private static Image img;
public static void main(String[] args) throws Exception {
String filename = "denmark.gif";
JFrame f = new JFrame("Image demo");
img =;
ImageDemo demo = new ImageDemo();
demo.setPreferredSize(new Dimension(img.getWidth(null), img.getHeight(null)));
f.getContentPane().add(new JScrollPane(demo));
f.setSize(800, 600);
f.setLocation(100, 100);;
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
Ho Ngoc Duc
Image example
 In the base directory (where
program runs): file
 The last argument in
drawImage() is null in our
 Reasonable if image can be
loaded instantly
 Otherwise: drawImage()
returns immediately even if
image not fully loaded 
ImageObserver object; it
gets notified when image
Ho Ngoc Duc
Components for text input
• JTextComponent provides methods for manipulating the text to be edited:
getText(), getDocument(), setText(), select(), getSelectedText()…
• Only displaying text (no editing): setEditable()
• JTextField and JPasswordField: single line
• JTextArea: multiple lines
• JEditorPane, JTextPane: editing and displaying rich texts
Ho Ngoc Duc
Using text components
 Easy: construct JTextField and JTextArea, add to content
 Harder: text scrolling
 Solution: wrap JTextArea in a JScrollPane
 Hardest part: listen to changes in JTextField
 No addTextListener or similar things in text components
 Changes notified via the model
• Application to check spelling of
country names
• Type part of name in a text field
• Matching names displayed in an
text area
• If text in text area too long:
scroll with scroll bar