Beruflich Dokumente
Kultur Dokumente
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
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.
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);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack(); setVisible(true); }
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, ...
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.
Playavisibleandinteractiveroleinaprograms GUI
JScrollPane JTabbedPane
ApanelsdefaultlayoutmanagerisFlowLayout.
Other layout managers can easily be set
panel.setLayout(new BorderLayout());
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 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
JOptionPane JProgressBar
JRootPane JSeparator JSlider JSplitPane JTabbedPane JTable JToolBar JToolTip JTree JViewport
JOptionPane Examples
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); } }
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
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
28
Containers - Layout
Each container has a layout manager Determines the size, location of contained widgets.
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
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? ...
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.
Listener type
ActionListener
ComponentListener
FocusListener ListSelectionListener
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
43
44
frame.pack(); frame.setVisible(true);
} public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Thank you"); } public static void main(String[] args) { new Events(); } }
45