Java Programming Creating a GUI with JFCSwing Vyacheslav

  • Slides: 31
Download presentation
Java Programming: Creating a GUI with JFC/Swing Vyacheslav Grebenyuk CTDE, AI dept. , Kh.

Java Programming: Creating a GUI with JFC/Swing Vyacheslav Grebenyuk CTDE, AI dept. , Kh. NURE (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006

Content About the JFC and Swing n Learning Swing by Example n (С) ЦТДО,

Content About the JFC and Swing n Learning Swing by Example n (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 2

About the JFC and Swing n JFC is short for Java Foundation Classes, which

About the JFC and Swing n JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 3

Features of the Java Foundation Classes 1 Feature Description Swing GUI Components Includes everything

Features of the Java Foundation Classes 1 Feature Description Swing GUI Components Includes everything from buttons to split panes to tables. Pluggable Look-and -Feel Support Gives any program that uses Swing components a choice of look and feel. For example, the same program can use either the Java or the Windows look and feel. Many more look-and-feel packages are available from various sources. As of v 1. 4. 2, the Java platform supports the GTK+ look and feel, which makes hundreds of existing look and feels available to Swing programs. Accessibility API Enables assistive technologies, such as screen readers and Braille displays, to get information from the user interface. (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 4

Features of the Java Foundation Classes 2 Java 2 D API Enables developers to

Features of the Java Foundation Classes 2 Java 2 D API Enables developers to easily incorporate high-quality 2 D graphics, text, and images in applications and applets. Java 2 D includes extensive APIs for generating and sending high-quality output to printing devices. Drag-and-Drop Support Provides the ability to drag and drop between Java applications and native applications. Internationalization Allows developers to build applications that can interact with users worldwide in their own languages and cultural conventions. With the input method framework developers can build applications that accept text in languages that use thousands of different characters, such as Japanese, Chinese, or Korean. (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 5

Which Releases Contain the Swing API? n The short answer is that the Swing

Which Releases Contain the Swing API? n The short answer is that the Swing API has been included in the Java 2 platform, Standard Edition (J 2 SETM) since its initial release (1. 2) (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 6

Swing API Content n In release 1. 4 of the Java platform, the Swing

Swing API Content n In release 1. 4 of the Java platform, the Swing API has 17 public packages: ¨ ¨ ¨ n javax. accessibility javax. swing. plaf javax. swing. text. html javax. swing. plaf. basic javax. swing. text. parser javax. swing. border javax. swing. plaf. metal javax. swing. text. rtf javax. swing. text javax. swing. plaf. multi javax. swing. tree javax. swing. event javax. swing. table javax. swing. undo javax. swing. filechooser javax. swing. colorchooser Fortunately, most programs use only a small subset of the API ¨ javax. swing. event (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 7

Example One: Your First Swing Program import javax. swing. *; public class Hello. World.

Example One: Your First Swing Program import javax. swing. *; public class Hello. World. Swing { private static void create. And. Show. GUI() { //Make sure we have nice window decorations. JFrame. set. Default. Look. And. Feel. Decorated(true); //Create and set up the window. JFrame frame = new JFrame("Hello. World. Swing"); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); //Add the ubiquitous "Hello World" label. JLabel label = new JLabel("Hello World"); frame. get. Content. Pane(). add(label); //Display the window. frame. pack(); frame. set. Visible(true); } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 8

Example One: Your First Swing Program 2 public static void main(String[] args) { //Schedule

Example One: Your First Swing Program 2 public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax. swing. Swing. Utilities. invoke. Later(new Runnable() { public void run() { create. And. Show. GUI(); } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 9

The basic code in every Swing program 1. 2. 3. 4. Import the pertinent

The basic code in every Swing program 1. 2. 3. 4. Import the pertinent packages Set up a top-level container Display the container Be thread-safe (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 10

Imports n import javax. swing. *; import java. awt. *; n import java. awt.

Imports n import javax. swing. *; import java. awt. *; n import java. awt. event. *; n n Swing components use the AWT infrastructure, including the AWT event model (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 11

Top-level Swing container n n n Every program with a Swing GUI must have

Top-level Swing container n n n Every program with a Swing GUI must have at least one top-level Swing container A top-level Swing container provides the support Swing components need for painting and event handling There are three commonly used top-level Swing containers: JFrame, JDialog, and (for applets) JApplet (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 12

JComponent n n With the exception of top-level containers, such as JFrame, all Swing

JComponent n n With the exception of top-level containers, such as JFrame, all Swing components descend from the JComponent class Hello. World. Swing uses a JComponent descendant called JLabel, which displays the text Hello World JLabel label = new JLabel("Hello World"); frame. get. Content. Pane(). add(label); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 13

Add components n Note that the label is added to the frame’s content pane

Add components n Note that the label is added to the frame’s content pane instead of to the frame itself. Every top-level container has a content pane that contains, directly or indirectly, all the visible components (except for menus and window decorations) in the top-level container (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 14

Program exit n To make the program exit when the Close button is clicked,

Program exit n To make the program exit when the Close button is clicked, we include this code: frame. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE); n In older programs frame. add. Window. Listener(new Window. Adapter() { public void window. Closing(Window. Event e) { System. exit(0); } }); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 15

Look and Feel n The following screenshots show the GUI of the Swing. Application,

Look and Feel n The following screenshots show the GUI of the Swing. Application, each one with a different look and feel String look. And. Feel = null; . . . look. And. Feel = UIManager. get. Cross. Platform. Look. And. Feel. Class. Name(); . . . try { UIManager. set. Look. And. Feel(look. And. Feel); } catch (Exception e) { }. . . // Create and show the GUI. . . (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 16

Setting Up Buttons and Labels n the code that initializes the button: JButton button

Setting Up Buttons and Labels n the code that initializes the button: JButton button = new JButton("I'm a Swing button!"); button. set. Mnemonic('i'); button. add. Action. Listener(/*. . . create an action listener. . . */); n the code that initializes and manipulates the label: private static String label. Prefix = "Number of button clicks: "; private int num. Clicks = 0; final JLabel label = new JLabel(label. Prefix + "0 "); label. set. Label. For(button); label. set. Text(label. Prefix + num. Clicks); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 17

Adding Components to Containers JPanel panel = new JPanel(new Grid. Layout(0, 1)); panel. add(button);

Adding Components to Containers JPanel panel = new JPanel(new Grid. Layout(0, 1)); panel. add(button); panel. add(label); panel. set. Border(Border. Factory. create. Empty. Border(. . . )); n layout manager - an object that determines the size and position of each component added to the container (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 18

Adding Borders Around Components n the code that adds a border to the panel:

Adding Borders Around Components n the code that adds a border to the panel: pane. set. Border(Border. Factory. create. Empty. Border( 30, //top 30, //left 10, //bottom 30) //right ); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 19

Handling Events Every time the user types a character or pushes a mouse button,

Handling Events Every time the user types a character or pushes a mouse button, an event occurs n Any object can be notified of the event n All the object has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source n (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 20

Swing. Application class public class Swing. Application implements Action. Listener {. . . JButton

Swing. Application class public class Swing. Application implements Action. Listener {. . . JButton button = new JButton("I'm a Swing button!"); button. add. Action. Listener(this); . . public void action. Performed(Action. Event e) { num. Clicks++; label. set. Text(label. Prefix + num. Clicks); } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 21

Event handler n Every event handler requires three pieces of code: ¨ In the

Event handler n Every event handler requires three pieces of code: ¨ In the declaration for the event handler class one line of code specifies that the class either implements a listener interface or extends a class that implements a listener interface ¨ Another line of code registers an instance of the event handler class as a listener on one or more components ¨ The event handler class has code that implements the methods in the listener interface (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 22

Kinds of events Some Events and Their Associated Event Listeners Act that Results in

Kinds of events Some Events and Their Associated Event Listeners Act that Results in the Event Listener Type User clicks a button, presses Enter while typing in a text field, or chooses a menu item Action. Listener User closes a frame (main window) Window. Listener User presses a mouse button while the cursor is over a component Mouse. Listener User moves the mouse over a component Mouse. Motion. Listener Component becomes visible Component. Listener Component gets the keyboard focus Focus. Listener Table or list selection changes List. Selection. Listener Any property in a component changes such as the text on a label Property. Change. Listener (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 23

Adding HTML n To use HTML in a component’s text, simply place the <HTML>

Adding HTML n To use HTML in a component’s text, simply place the <HTML> tag at the beginning of the text string and then use any valid HTML code in the remainder of the string button = new JButton("<html><b><u>T</u>wo</b> lines</html>"); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 24

Adding an Icon n Some Swing components can be decorated with an icon--a fixed-size

Adding an Icon n Some Swing components can be decorated with an icon--a fixed-size image Image. Icon convert. Icon = create. Image. Icon("images/convert. gif", "Convert temperature"); . . . JButton convert. Temp = new JButton(icon); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 25

Setting the Default Button converter. Frame. get. Root. Pane(). set. Default. Button(convert. Temp); (С)

Setting the Default Button converter. Frame. get. Root. Pane(). set. Default. Button(convert. Temp); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 26

Using Layout Managers The Java platform supplies six commonly used layout managers: Border. Layout,

Using Layout Managers The Java platform supplies six commonly used layout managers: Border. Layout, Box. Layout, Flow. Layout, Grid. Bag. Layout, and Spring. Layout n JPanel objects use Flow. Layout by default content panes (the main containers in JApplet, JDialog, and JFrame objects) use Border. Layout by default n (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 27

Using Layout Managers 2 n As a rule, the only time you have to

Using Layout Managers 2 n As a rule, the only time you have to think about layout managers is when you create a JPanel or add components to a content pane JPanel pane = new JPanel(new Border. Layout()); … Container content. Pane = frame. get. Content. Pane(); content. Pane. set. Layout(new Flow. Layout()); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 28

Compound Borders // Add border around the select panel select. Panel. set. Border(Border. Factory.

Compound Borders // Add border around the select panel select. Panel. set. Border(Border. Factory. create. Compound. Border( Border. Factory. create. Titled. Border("Select Phase"), Border. Factory. create. Empty. Border(5, 5, 5, 5))); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 29

Combo Boxes JCombo. Box phase. Choices = null; . . . //Create combo box

Combo Boxes JCombo. Box phase. Choices = null; . . . //Create combo box with lunar phase choices. String[] phases = { "New", "Waxing Crescent", "First Quarter", "Waxing Gibbous", "Full", "Waning Gibbous", "Third Quarter", "Waning Crescent" }; phase. Choices = new JCombo. Box(phases); phase. Choices. set. Selected. Index(START_INDEX); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 30

Handling Events on a Combo Box n The combo box fires an action event

Handling Events on a Combo Box n The combo box fires an action event when the user selects an item from the combo box's drop-down list phase. Choices. add. Action. Listener(this); . . . public void action. Performed(Action. Event event) { if ("combo. Box. Changed". equals(event. get. Action. Command())) { //Update the icon to display the new phase. Icon. Label. set. Icon( images[phase. Choices. get. Selected. Index()]); } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006 31