Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Similar documents
PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Graphic User Interfaces. - GUI concepts - Swing - AWT

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

PIC 20A GUI with swing

Window Interfaces Using Swing Objects

AP CS Unit 11: Graphics and Events

Window Interfaces Using Swing Objects

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Top-Level Containers

Introduction to the JAVA UI classes Advanced HCI IAT351

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Programming graphics

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Java. GUI building with the AWT

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Introduction. Introduction

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Graphical User Interfaces 2

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Building Java Programs Bonus Slides

Dr. Hikmat A. M. AbdelJaber

Graphical User Interfaces. Swing. Jose Jesus García Rueda

Graphical User Interfaces. Comp 152

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Part I: Learn Common Graphics Components

Java Programming Lecture 6

CHAPTER 2. Java Overview

SampleApp.java. Page 1

Systems Programming Graphical User Interfaces

User interfaces and Swing

CS 251 Intermediate Programming GUIs: Components and Layout

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Packages: Putting Classes Together

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

CSE 331. Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Lecture 5: Java Graphics

Layouts and Components Exam

2110: GUIS: Graphical User Interfaces

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Dr. Hikmat A. M. AbdelJaber

Graphical User Interfaces 2

MIT AITI Swing Event Model Lecture 17

GUI in Java TalentHome Solutions

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

encompass a group of features for building Graphical User Interfaces (GUI).

G51PRG: Introduction to Programming Second semester Applets and graphics

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

DM503 Programming B. Peter Schneider-Kamp.

14.2 Java s New Nimbus Look-and-Feel 551 Sample GUI: The SwingSet3 Demo Application As an example of a GUI, consider Fig. 14.1, which shows the SwingS

INTRODUCTION TO (GUIS)

Part 3: Graphical User Interface (GUI) & Java Applets

Graphical User Interfaces 2

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Window Interfaces Using Swing. Chapter 12

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Using Several Components

COMP16121 Sample Code Lecture 1

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Chapter 12 Advanced GUIs and Graphics

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

JAVA NOTES GRAPHICAL USER INTERFACES

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS

H212 Introduction to Software Systems Honors

Graphical User Interfaces in Java

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

Graphical User Interfaces

The Java Programming Language Basics. Identifiers, Keywords, and Types. Expressions and Flow Control. Object-Oriented Programming. Objects and Classes

Chapter 7: A First Look at GUI Applications

Chapter 6: Graphical User Interfaces

Graphical User Interfaces in Java - SWING

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers

Unit 6: Graphical User Interface

Graphical User Interface (GUI) and Object- Oriented Design (OOD)

Class 16: The Swing Event Model

CS 251 Intermediate Programming GUIs: Event Listeners

Programming Languages and Techniques (CIS120e)

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

GUI Design. Overview of Part 1 of the Course. Overview of Java GUI Programming

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

JFrame In Swing, a JFrame is similar to a window in your operating system

Chapter 13 GUI Basics. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Swing I CHAPTER EVENT-DRIVEN PROGRAMMING 921 Events and Listeners 921

Programming Languages and Techniques (CIS120)

Swing I Event-Driven Programming Buttons, Events, and Other Swing Basics Containers and Layout Managers 946

Chapter 12 GUI Basics

Transcription:

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