Datenbank-Praktikum Universität zu Lübeck Sommersemester 2006 Lecture: Swing Ho Ngoc Duc 1
Learning objectives GUI applications Font, Color, Image Running Applets as applications Swing Components q q Text input Scrolling Reference: q Core Java, Ch. 7 & 9 q TIJ, Ch. 14 q Tutorial, Trail: Creating a GUI with JFC/Swing Ho Ngoc Duc 2
Class javax.swing.jframe Each GUI application must have a container that holds everything else q 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 3
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 4
Frame positioning settitle(string) changes the text of title bar setresizeable(boolean) To set size and position q setsize(width, height) q setlocation(x, y) q setbounds(x, y, width, height) q 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 5
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 6
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: q settext(string): change the displayed text q setenabled(boolean): enable/disable button The button will change its appearance Ho Ngoc Duc 7
JTextField Input a single line of text Constructors: q JTextField() q JTextField(String): with a text q JTextField(String, int): with text and number of columns Methods: gettext(), settext(string) Ho Ngoc Duc 8
Tooltips and HTML JComponent has a method settooltiptext() q When move mouse over component: tooltip text shows short info about it JButton b = new JButton("Compute"); b.settooltiptext("click to compute the product"); q 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 HTMLformatted text JLabel lb = new JLabel("<html><h2>Big text</h2>"); JLabel and various buttons (JButton, JCheckBox, JRadioButton ) can contain an Icon (javax.swing.icon) q Usually: javax.swing.imageicon Ho Ngoc Duc 9
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 10
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 q getpreferredsize() already implemented for standard components q If you write your own components: should override it Ho Ngoc Duc 11
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 q but normally layout is done by a layout manager Layout manager: q object associated with a container q implements some policy for laying out the components in that container q Different types of layout manager implement different policies Ho Ngoc Duc 12
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 q If next component does not fit: next row q Resizing the JPanel: components rearranged q Components have their "natural" size If we want to use a certain layout manager for a container: call setlayout() Ho Ngoc Duc 13
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 q q BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST, BorderLayout.WEST, and BorderLayout. CENTER Adding without specifying an area: CENTER Ho Ngoc Duc 14
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 q one of these numbers may be 0 q cells have the same size q stretched / compressed to fit in container Ho Ngoc Duc 15
Absolute positioning It is also possible to set the absolute position of the graphical components q Set a null layout manager for your Container: setlayout(null). q Call setbounds() for each component, passing a bounding rectangle in pixel coordinates Some GUI builders use this approach extensively q usually not the best way to generate code Ho Ngoc Duc 16
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 17
The Swing Event Model Swing components can "fire" different kinds of events q 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 q When an event is fired, it is received by any listener that has registered to respond to the event, Many event/listener types q q q ActionEvent / ActionListener MouseEvent / MouseListener, MouseMotionListener KeyEvent / KeyListener Ho Ngoc Duc 18
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 19
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 20
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 21
Image example In the base directory (where program runs): file denmark.gif The last argument in drawimage() is null in our case q Reasonable if image can be loaded instantly q Otherwise: drawimage() returns immediately even if image not fully loaded ImageObserver object; it gets notified when image loaded Ho Ngoc Duc 22
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 23
Using text components 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 Easy: construct JTextField and JTextArea, add to content pane Harder: text scrolling q Solution: wrap JTextArea in a JScrollPane Hardest part: listen to changes in JTextField q No addtextlistener or similar things in text components q Changes notified via the model Ho Ngoc Duc 24