Sie sind auf Seite 1von 45

A Quick Java Swing Tutorial

Introduction
Swing A set of GUI classes
Part of the Java's standard library Much better than the previous library: AWT Abstract Window Toolkit

Highlights
A rich set of widgets Widget: Any GUI element (also called: components) Contents and shape are separated (MVC support) Fine-grained control over the behavior and look and feel Platform independent Isolates the programmer from the operating system's GUI
2

Swing Components
Containers Contain and manage other components. Top Level/Internal Examples: JFrame (Top Level), JScrollPane, JPanel. Basic controls Atomic components Used for showing ouput and/or getting some input Inherits JComponent Examples: JButton, JLabel, JTextArea, JTable, Jlist Usually every Swing class extends the corresponding AWT class For backward-compatibility reasons
3

Top Level Containers


Every program that presents a Swing GUI contains at least one top-level container. A Top level container provides the support that Swing components need to perform their painting and event-handling. Swing provides three top-level containers:
JFrame (Main window) JDialog (Secondary window) JApplet (An applet display area within a browser window)

Top Level Containers (cont)


To appear on screen, every GUI component must be part of a containment hierarchy, with a top-level container as its root. Each top-level container has a content pane that contains visible components in that top-level containersGUI.

Dont add a component directly to a top-level container.

JFrame
A frame implemented as an instance of the JFrame class, is a window that has decorations such as a border, a title and buttons for closing and iconifying the window.
The decorations on a frame are platform dependent.

Applications with a GUI typically use at least one frame.

Example 1
import javax.swing.*; public class HelloWorldSwing { public static void main(String[] args) { JFrame frame = new JFrame("HelloWorldSwing"); final JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); frame.setVisible(true); } }

pack() causes a window to be sized to fit the preferred size and layouts of its sub-components

Example 2
import javax.swing.*; public class HelloWorldFrame extends JFrame { public HelloWorldFrame() { super(HelloWorldSwing); final JLabel label = new JLabel("Hello World"); getContentPane().add(label);

In this example a custom frame is created

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack(); setVisible(true); }

public static void main(String[] args) {


HelloWorldFrame frame = new HelloWorldFrame(); } }

JDialog
Every dialog is dependent on a frame
Destroying a frame destroys all its dependent dialogs. When the frame is iconified, its dependent dialogs disappear from the screen. When the frame is deiconified, its dependent dialogs return to the screen.

A dialog can be modal. When a modal dialog is visible it blocks user input to all other windows in the program.

JDialog (cont)
To create custom dialogs, use the JDialog class directly (as in the previous examples). Swing provides several standard dialogs
JProgressBar, JFileChooser, JColorChooser, ...

The JOptionPane class can be used to create simple modal dialogs


icons, title, text and buttons can be customized.

JComponent
JComponent is the base class for all Swing components except top-level containers.
JLabel, JButton, JList, JPanel, JTable, ...

To use a component that inherits from JComponent, it must be placed in a containmenthierarchywhosbaseisatoplevel container.

Intermediate Level Containers


Also known as panels or panes Simplify the positioning of other components.
JPanel

Playavisibleandinteractiveroleinaprograms GUI
JScrollPane JTabbedPane

ApanelsdefaultlayoutmanagerisFlowLayout.
Other layout managers can easily be set
panel.setLayout(new BorderLayout());

Intermediate Level Containers (cont)


Bydefault,panelsdontpaintanything except for their background. By default, panels are opaque.
An opaque panel can be set as a top-level containerscontentpane. transparent (non-opaque) panels draw no background.

My First Swing Program


import javax.swing.*; import java.awt.BorderLayout; public class First { public static void main(String[] args) { JFrame frame = new JFrame("My First Frame"); // operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new JLabel("I Love Swing"), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }

14

HelloWorldFrame.java
import javax.swing.*; public class HelloWorldFrame extends JFrame { public HelloWorldFrame() { super("HelloWorldSwing"); final JLabel label = new JLabel("Hello World"); getContentPane().add(label); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); } public static void main(String[] args) { HelloWorldFrame frame = new HelloWorldFrame(); } }

Swing Component Hierarchy


Container
JComponent
AbstractButton
JButton JMenuItem JCheckBoxMenuItem JMenu JRadioButtonMenuItem JToggleButton JCheckBox JRadioButton

Swing Components

17

Swing Components

18

Contd
JComponent
JComboBox JLabel JList JMenuBar JPanel JPopupMenu JScrollBar JScrollPane

Contd
JComponent
JTextComponent
JTextArea JTextField
JPasswordField

JTextPane
JHTMLPane

More Components
FontChooser JColorChooser JDesktopIcon JDirectoryPane
JFileChooser

JImagePreviewer JInternalFrame JLayeredPane


JDesktopPane

JOptionPane JProgressBar

JRootPane JSeparator JSlider JSplitPane JTabbedPane JTable JToolBar JToolTip JTree JViewport

JOptionPane Examples

Top Level Containers: JDialog


javax.swing.JDialog:
More simple and limited than frames Typically used for showing a short message on the screen Also has a border and a title bar May have an owner If the owner is invisible the dialog will also be invisible
JOptionPane.showMessageDialog(null, "4+2=6");

Use the static method of JoptionPane to show standard dialog boxes:

23

JOptionPane Example
import javax.swing.*; public class DialogDemo extends JFrame { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "Hello Sir, How are You !"); JOptionPane.showMessageDialog(null,"Message will print","This will be the title",JOptionPane.INFORMATION_MESSAGE); String value=JOptionPane.showInputDialog(null,"Enter Value"); String value2=JOptionPane.showInputDialog(null,"Enter the secret code to continue (label)", "Secret code needed (title)",JOptionPane.WARNING_MESSAGE); /* ERROR_MESSAGE ,INFORMATION_MESSAGE PLAIN_MESSAGE, QUESTION_MESSAGE WARNING_MESSAGE */ int choice2 = JOptionPane.showOptionDialog(null,"You really want to quit?","Quit?",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); } }

Top Level Containers: JFileChooser

javax.swing.JFileChooser:
Allows the the user to choose a file Supportsopenandsave:showOpenDialog(),showSaveDialog()
JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) System.out.println("File: " + fc.getSelectedFile());
25

Top Level Containers: JFrame


javax.swing.JFrame:
Top-level window with a title and a border. Usually used as a program's main window

26

More on JFrame
Made of several layers Widgets are added to the Content Pane layer. Use getContentPane() to obtain it Other layers are used for customizing the window's appearence

27

Internal Containers
Not Top level containers Can contain other non-top level components Examples:
JScrollPane: Provides a scrollable view of its components
JSplitPane: Separates two components

JTabbedPane: User chooses which component to see

28

Containers - Layout
Each container has a layout manager Determines the size, location of contained widgets.

Setting the current layout of a container:


void setLayout(LayoutManager lm) LayoutManager implementing BorderLayout BoxLayout FlowLayout GridLayout

classes:

29

FlowLayout
Default manager for JPanels. Components are arranged from left to right, in the order they are added to the container. Simplest to use but least capable.

BorderLayout
Default manager for JFrames, JDialog, and JApplet. Defines five areas where components can be positioned: North (top), South (bottom), East (right), West (left) and Center (middle of container). The default area is Center. Only the last component added to an area will be visible. Components that are placed in Center are made as large as possible for the current window size. Components in the other four areas are made proportionally smaller to give more room for the Center area. Specify which area a component is added into by passing a second argument to the container'sadd() method.

BoxLayout
Components are arranged in either a vertical or horizontal row, in the order they were added to the container. Each component can request a certain preferred and maximum size. The orientation of the row is specified by a constructor parameter.

GridLayout
Components are made the same size and placed in a grid configuration, one per cell, top to bottom, and left to right in the order they were added to the container. The size of the grid is specified by two constructor parameters. Forces all components to be the same size
as wide as the widest component's preferred width ashighasthehighestcomponentspreferredheight

GridBagLayout
Most flexible layout manager, also most complicated to use. Intended for use by GUI builders. Defines a grid similar to that used by GridLayout, but rows and columns need not be the same size, and controls can span multiple cells. Component sizes are defined via a GridBagConstraints object and set by a call toGridBagLayout's setConstraints() method before the component is added to the container.

null
No layout manager. Components must be positioned and sized manually by the programmer.

Containers - Layout

36

First Swing Program Revisited


import javax.swing.*; import java.awt.BorderLayout; Create a frame public class First { public static void main(String[] args) { JFrame frame = new JFrame("My First Frame"); Choose the border // operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new JLabel("I Love Swing"), BorderLayout.CENTER); frame.pack(); Create a text frame.setVisible(true); label } Add the label to Specify CENTER } the content pane as the layout position
37

layout

Input
So we now know how to present widgets on the screen A program also needs to react to the user's actions Examples:
When the user presses a button we want to save a file Whentheuserclosestheprogramwewanttoaskareyou sure? ...

Swing mechanism: Events and Listeners

38

Events Handling
Every time a user types a character or pushes a mouse button, an event occurs. Any object can be notified of an event by registering as an event listener on the appropriate event source. Multiple listeners can register to be notified of events of a particular type from a particular source.

Types of Event Listeners


Act that results in event
User clicks a button, presses Return while typing in a text field, or chooses a menu item User closes a frame (main window) User presses a mouse button while the cursor is over a component User moves the mouse over a component

Listener type
ActionListener

WindowListener MouseListener MouseMotionListener

Component becomes visible


Component gets the keyboard focus Table or list selection changes

ComponentListener
FocusListener ListSelectionListener

Implementing an Event Handler


Implement a listener interface or extend a class that implements a listener interface. Register an instance of the event handler class as a listener upon one or more components. Implement the methods in the listener interface to handle the event. Lesson: Writing Events Handlers

Events, Listeners
Swing defines all sorts of Listener interfaces E.g.: ActionListener, MouseMotionListener, WindowListener, ...
public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); } public interface MouseMotionListener extends EventListener { public void mouseDragged(MouseEvent e); public void mouseMoved(MouseEvent e); }

There are default (empty) implementations for many of the listeners E.g.: MouseMotionAdapter, WindowAdapter
42

Events, Listeners (cont.)


A listener is an object that implements a listener interface If we need to react to an event (on a certain widget) we register a listener object with that widget E.g.: addActionListener() registers an action listener with its receiver: JButton button = new JButton(); button.addActionListener(this); When an event occurs, all registered listeners are notified The appropriate listener method (e.g: actionPerformed()) is invoked An object describing the event is passed as a parameter

43

Event Handling Demo: GUI

44

Event Handling Demo: Code


import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Events implements ActionListener { public Events() { JFrame frame = new JFrame("Events"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new FlowLayout()); JButton b = new JButton("Click me!"); b.addActionListener(this); frame.getContentPane().add(b);

frame.pack(); frame.setVisible(true);
} public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Thank you"); } public static void main(String[] args) { new Events(); } }
45

Das könnte Ihnen auch gefallen