Download Создание графических интерфейсов пользователя с помощью

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Programming:
Creating a GUI with
JFC/Swing
Vyacheslav Grebenyuk
CTDE, AI dept., KhNURE
Content
About the JFC and Swing
 Learning Swing by Example

(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
2
About the JFC and Swing

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 from buttons to split panes to tables.
Pluggable Lookand-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 v1.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 2D API
Enables developers to easily incorporate high-quality 2D graphics,
text, and images in applications and applets. Java 2D 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?

The short answer is that the Swing API
has been included in the Java 2 platform,
Standard Edition (J2SETM) since its initial
release (1.2)
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
6
Swing API Content

In release 1.4 of the Java platform, the Swing API has 17
public packages:







javax.accessibility javax.swing.plaf
javax.swing.text.html
javax.swing
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
javax.swing.event
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
7
Example One: Your First Swing
Program
import javax.swing.*;
public class HelloWorldSwing {
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
}
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
8
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.SwingUtilities.invokeLater(new
Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
9
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

import javax.swing.*;
import java.awt.*;
 import java.awt.event.*;


Swing components use the AWT
infrastructure, including the AWT event
model
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
11
Top-level Swing container



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


With the exception of top-level containers, such
as JFrame, all Swing components descend from
the JComponent class
HelloWorldSwing uses a JComponent
descendant called JLabel, which displays the
text Hello World
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
13
Add components

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

To make the program exit when the Close button
is clicked, we include this code:
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);

In older programs
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
15
Look and Feel

The following screenshots show the GUI
of the SwingApplication, each one with a
different look and feel
String lookAndFeel = null;
...
lookAndFeel =
UIManager.getCrossPlatformLookAndFeelClassName();
...
try {
UIManager.setLookAndFeel(lookAndFeel);
} catch (Exception e) { }
...// Create and show the GUI...
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
16
Setting Up Buttons and Labels

the code that initializes the button:
JButton button = new JButton("I'm a Swing button!");
button.setMnemonic('i');
button.addActionListener(/*...create an action
listener...*/);

the code that initializes and manipulates the
label:
private static String labelPrefix = "Number of button
clicks: ";
private int numClicks = 0;
final JLabel label = new JLabel(labelPrefix + "0
");
label.setLabelFor(button);
label.setText(labelPrefix + numClicks);
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
17
Adding Components to Containers
JPanel panel = new JPanel(new GridLayout(0,1));
panel.add(button);
panel.add(label);
panel.setBorder(BorderFactory.createEmptyBorder(...));

layout manager - an object that
determines the size and position of each
component added to the container
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
18
Adding Borders Around
Components

the code that adds a border to the panel:
pane.setBorder(BorderFactory.createEmptyBorder(
30, //top
30, //left
10, //bottom
30) //right
);
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
19
Handling Events
Every time the user types a character or
pushes a mouse button, an event occurs
 Any object can be notified of the event
 All the object has to do is implement the
appropriate interface and be registered as
an event listener on the appropriate event
source

(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
20
SwingApplication class
public class SwingApplication implements
ActionListener {
...
JButton button = new JButton("I'm a Swing
button!");
button.addActionListener(this);
....
public void actionPerformed(ActionEvent e) {
numClicks++;
label.setText(labelPrefix + numClicks);
}
}
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
21
Event handler

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 the Event
Listener Type
User clicks a button, presses Enter while typing
in a text field, or chooses a menu item
ActionListener
User closes a frame (main window)
WindowListener
User presses a mouse button while the cursor is
over a component
MouseListener
User moves the mouse over a component
MouseMotionListener
Component becomes visible
ComponentListener
Component gets the keyboard focus
FocusListener
Table or list selection changes
ListSelectionListener
Any property in a component changes such as
the text on a label
PropertyChangeListener
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
23
Adding HTML

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><br>lines</html>");
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
24
Adding an Icon

Some Swing components can be
decorated with an icon--a fixed-size image
ImageIcon convertIcon =
createImageIcon("images/convert.gif",
"Convert temperature");
...
JButton convertTemp = new JButton(icon);
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
25
Setting the Default Button
converterFrame.getRootPane().
setDefaultButton(convertTemp);
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
26
Using Layout Managers
The Java platform supplies six commonly
used layout managers: BorderLayout,
BoxLayout, FlowLayout, GridLayout,
GridBagLayout, and SpringLayout
 JPanel objects use FlowLayout by
default content panes (the main containers
in JApplet, JDialog, and JFrame
objects) use BorderLayout by default

(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
27
Using Layout Managers 2

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 BorderLayout());
…
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
28
Compound Borders
// Add border around the select panel
selectPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Select Phase"),
BorderFactory.createEmptyBorder(5,5,5,5)));
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
29
Combo Boxes
JComboBox phaseChoices = null;
...
//Create combo box with lunar phase choices.
String[] phases = { "New", "Waxing Crescent", "First Quarter",
"Waxing Gibbous", "Full", "Waning Gibbous",
"Third Quarter", "Waning Crescent" };
phaseChoices = new JComboBox(phases);
phaseChoices.setSelectedIndex(START_INDEX);
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
30
Handling Events on a Combo Box

The combo box fires an action event when the user selects an
item from the combo box's drop-down list
phaseChoices.addActionListener(this);
...
public void actionPerformed(ActionEvent event) {
if
("comboBoxChanged".equals(event.getActionCommand()))
{
//Update the icon to display the new phase
phaseIconLabel.setIcon(
images[phaseChoices.getSelectedIndex()]);
}
}
(С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
31