Java AWT and Swing API

advertisement

Java AWT and Swing API

Dr Salim Vanak

s.vanak@dcs.shef.ac.uk

File swing.tex – p. 1

GUI Widgets

• Java has two GUI (Graphics User Interface) packages, the original Abstract

Windows Toolkit or AWT and the newer Swing

• AWT used the native operating system’s window routines and therefore the visual effect was dependent on the run time system platform.

• Swing allows three modes: a unified ’Java’ look and feel [the default], the native platform look, or a specific platform’s look.

• Swing has quite a large overhead. Eclipse SWT tires to get the best of both worlds.

• We will be focusing on Swing and bit of AWT.

File swing.tex – p. 2

Containers

• Containers hold GUI controls or widgets. For example text fields check boxes etc.

• Other Widgets can be added to a Container using its add(Component) method.

• A Container is also a Component, this allows containers to be nested in order to create complex layouts.

• JPanel is one of the most commonly used containers.

• The is also the Box container for creating Row or Column wise layouts.

JPanel panel = new JPanel();

JTextField field1 = new JTextField(); panel.add(new JLabel("Field 1")); panel.add(field1); panel.add(new JButton("Ok"));

File swing.tex – p. 3

Layout Managers

• As soon as you have more than one or two widgets (ie components or controls), you need to arrange them in a logical and pleasing way.

• A JPanel is a Container, which means that it can contain other components. GUI design in Java relies on a layered approach where each layer uses an appropriate layout manager.

• Layout managers are interface classes that align components so they neither crowd each other nor overlap.

• Each layout manager defines methods that arrange components within a container, and each component you place within a Container can also be a container itself.

• The Java platform supplies layout managers that range from the very simple

FlowLayout and GridLayout.

• to the special purpose BorderLayout and CardLayout, to the very flexible BoxLayout and GridBagLayout.

• SpringLayout is a new layout manager that uses the concepts of springs and struts to help design well-positioned containers.

File swing.tex – p. 4

FlowLayout

• FlowLayout is used to arrange components in rows across the width of a container

• FlowLayout components automatically wrap or move to the next row when required.

• When you use FlowLayout, each component retains its default size (i.e. a JButton will be large enough to hold its text.

• A component might become partially obscured or change position or wrap due to the size of the container.

• You can fix a minimum size for the container by calling the

JComponent.setMinimumSize(int, int) method.

File swing.tex – p. 5

GridLayout

• uses a simple row and column grid metaphor for layout. All elements are of the same width and height and scale similarly when resized. The constructor is

GridLayout(rows,columns,x-spacing, y-spacing)

BoxLayout

Places items in a single row or column. An example is:

JPanel panel = new JPanel();

BoxLayout box = new BoxLayout(panel,Boxlayout.Y_AXIS));

You may be better off using the Box class instead of BoxLayout.

Card Layout

• CardLayout presents widgets one at a time as if cards in a deck.

• A common use is a slideshow viewer where different panes are displayed one at a time.

File swing.tex – p. 6

BorderLayout

• BorderLayout is used when you add components to a maximum of five sections arranged in North, South, East, West and Center positions.

• BorderLayout is the default manager for all content panes.

• When you place exactly five components in a container and use BorderLayout, each component fills one entire region.

• When the program runs, the Layout Manager determines the exact size of each component based on the component’s contents.

• North, South, East, West containers will take up their preferred sizes.

• the Center component will take up the rest of the space.

• Any empty component regions disappear from the layout.

JPanel p = new JPanel(new BorderLayout()); p.add(new JLabel("North"), BorderLayout.NORTH); p.add(new JLabel("South"), BorderLayout.SOUTH); p.add(new JLabel("East"), BorderLayout.EAST); p.add(new JLabel("West"), BorderLayout.WEST); p.add(new JLabel("Center"), BorderLayout.CENTER);

File swing.tex – p. 7

Top Level Components

• Swings top level contains are: JFrame, JDialog, JWindow, JApplet.

• The most frequently used top level container is JFrame, and contains methods such as:

◦ setBounds(x,y,w,h)

◦ setLocation(x,y)

◦ setSize(w,h)

◦ setResizable(bool)

◦ setTitle(str)

◦ setVisible(bool)

◦ isResizable()

◦ getTitle()

◦ getContentPane()

File swing.tex – p. 8

Creating a frame

All GUI processing must occur within the Event Dispatch Thread.

The following code creates a frame in the “main” thread.

public static void main(String[] args) {

JFrame app = new JFrame(); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.setVisible(true);

}

Creating a frame in the EDT public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() { public void run() {

JFrame app = new JFrame(); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.setVisible(true);

}

});

}

File swing.tex – p. 9

The Content Pane

• A JFrame is made up of many components.

• When adding components to a JFrame you must add the compoents to the Content

Pane of the JFrame.

• In Java 1.4.x you must do frame.getContentPane().add(Component)

• In Java 1.5 has make JFrame.add(Component) the same as frame.getContentPane().add(Component)

File swing.tex – p. 10

Basic Event Listeners

• GUIs are event-based. That is they respond to buttons, keyboard input or mouse activities.

• Java uses event listeners to monitor activity on specified objects and react to specific conditions.

• The most common Listener interface for GUI component is ActionListener.

• An ActionEvent is generated when ever a component receives a user actions. e.g.

clicking a JButton, pressing enter on a JTextField.

• Other listener interfaces include, Focus Listener, MouseListener,

ListSelectionListener.

• For listener interfaces that contain more than one method, the API also has Adaptor classes for the interface.

• The Adaptor is simply a class that implements the Listener as empty methods.

File swing.tex – p. 11

Creating listeners.

• There are two methods: Have the class implement the listener, or create a new class.

class MyPanel extends JPanel implements ActionListener {

JButton b = new JButton("Ok");

MyPanel() { super(); b.addActionListener(this);

}

} public void actionPerformed(ActionEvent e) { if (e.getSource() == b) {

// Do something

}

}

File swing.tex – p. 12

Anonymous Listeners class MyPanel extends JPanel {

JButton b = new JButton("Ok");

}

MyPanel() { super(); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {

// Do something

}

});

}

File swing.tex – p. 13

Anonymous Adaptors

For Listener like focus listener that contain many methods, using the adaptor class is better.

class MyPanel extends JPanel {

JButton b = new JButton("Ok");

}

MyPanel() { super(); b.addActionListener(new FocusAdaptor() {

}

}); public void focusLost(FocusEvent e) {

// Do something when focus is lost.

}

File swing.tex – p. 14

Simple Dialog Boxes

• Simple dialogs appear in popup windows.

• Dialogs include:

◦ Short messages or information screens

◦ confirmation boxes.

◦ input prompts for string information.

• Swing uses the JOptionPane class to provide methods for each type of dialog.

• Each method has a first parameter that points to a parent (ie. window that it appears in) or null (default to the current window).

• Dialog boxes will block until the user returns an input. Removing the need to listen for an event.

File swing.tex – p. 15

Dialog Examples

JOptionPane.showMessageDialog(null,"This is just a message",

"Message Dialog",JOptionPane.PLAIN_MESSAGE); int pressed = JOptionPane.showConfirmBox(null,"Everything aok"); if (pressed == JOptionPane.YES_OPTION) {

// do the action for confirmation

}

String user_data = JOptionPane.showInputDialog(null,"What’s your name");

File swing.tex – p. 16

Download