Datenbank-Praktikum - Universität zu Lübeck

snottybugbearΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 3 χρόνια και 11 μήνες)

131 εμφανίσεις

Ho Ngoc Duc 1
Datenbank-Praktikum
Universität zu Lübeck
Sommersemester 2006
Lecture: Swing
Ho Ngoc Duc
2
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
3
Class javax.swing.JFrame
 Each GUI application must have a container
that holds everything else
 Top-level container (not contained in another
container)
 In Swing: JFrame
 Method getContentPane() gives the JFrame's
content pane where other components can
be added to
Ho Ngoc Duc
4
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);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.show();
}
}
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
5
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
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
• JFrame inherits all methods of ancestors
• Location of a JFrame specified relative
to the whole screen (not to another
component)
Ho Ngoc Duc
6
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
7
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
8
JTextField
 Input a single line of text
 Constructors:
 JTextField()
 JTextField(String): with a text
 JTextField(String, int): with text and number of
columns
 Methods: getText(), setText(String)
Ho Ngoc Duc
9
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
10
HTML label example
public class FrameDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Hello Swing");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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);
right.setForeground(Color.RED);
String txt2 = "<html>This button has a <b><i>red</i></b> text";
right.setToolTipText(txt2);
f.pack(); // What happnes if you call f.setSize(200, 200); ?
f.setVisible(true);
}
}
Ho Ngoc Duc
11
Fancy buttons and labels
 Font and color of the text
displayed on a component
can be set with setFont(),
setBackground() and
setForeground()
 When pack() called:
calculate space needed to
accommodate all
components
 getPreferredSize()
already implemented for
standard components
 If you write your own
components: should
override it
Ho Ngoc Duc
12
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
13
FlowLayout
 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
14
BorderLayout
 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
15
GridLayout
 A GridLayout allows you to build a table of
components
 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
16
Absolute positioning
 It is also possible to set the absolute position
of the graphical components
 Set a null layout manager for your Container:
setLayout(null).
 Call setBounds() for each component, passing a
bounding rectangle in pixel coordinates
 Some GUI builders use this approach
extensively
 usually not the best way to generate code
Ho Ngoc Duc
17
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
18
The Swing Event Model
 Swing components can "fire" different kinds of
events
 Each type of event is represented by a distinct class
 We can write listeners (implementors of associated
listener interface) and register them to certain
components
 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
19
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());
add(b1);
add(b2);
b1.addActionListener(new AL());
}
class AL implements ActionListener {
public void actionPerformed(ActionEvent e) {
b2.setEnabled(!b2.isEnabled());
}
}
public static void main(String[] args) {
// …
}
}
Ho Ngoc Duc
20
Using images
 In Java 1.4, reading an image is easy with
javax.imageio.ImageIO
String filename = "...";
Image image = ImageIO.read(new 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
21
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");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
img = javax.imageio.ImageIO.read(new java.io.File(filename));
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);
f.show();
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
Ho Ngoc Duc
22
Image example
 In the base directory (where
program runs): file
denmark.gif
 The last argument in
drawImage() is null in our
case
 Reasonable if image can be
loaded instantly
 Otherwise: drawImage()
returns immediately even if
image not fully loaded 
ImageObserver object; it
gets notified when image
loaded
Ho Ngoc Duc
23
Components for text input
java.lang.Object
+-java.awt.Component
+-java.awt.Container
+-javax.swing.JComponent
+-javax.swing.text.JTextComponent
+-javax.swing.JTextField
+-javax.swing.JPasswordField
+-javax.swing.JTextArea
+-javax.swing.JEditorPane
+-javax.swing.JTextPane
• 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
24
Using text components
 Easy: construct JTextField and JTextArea, add to content
pane
 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