MIT AITI 2003 Lecture 16. Swing Part I

Post on 18-Jan-2016

34 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

MIT AITI 2003 Lecture 16. Swing Part I. Let’s swing and have some fun !!!. Lecture Preview. Over the next 2 lectures, we will introduce you to the techniques necessary to build graphic user interfaces (GUI) for your applications. - PowerPoint PPT Presentation

Transcript

MIT AITI 2003MIT AITI 2003Lecture 16. Lecture 16. Swing Part ISwing Part I

Let’s swing

and have some fun !!!

Lecture PreviewLecture Preview

Over the next 2 lectures, we will introduce you to the techniques necessary to build graphic user interfaces (GUI) for your applications.

1. Learning Swing basic concepts: components and containers, fonts, colors, borders, layout;

2. Constructing Swing interfaces;3. Using the Swing Event Model.

What is a Swing Application?What is a Swing Application?-- A simple Greeting Swing Application-- A simple Greeting Swing Application

import javax.swing.*;

public class MyTest extends JFrame {

JLabel myLabel = new JLabel(" Hello, World!");

public MyTest() {

super("MyTest");

setSize(350, 100);

getContentPane().add(myLabel);

setVisible(true);

setDefaultCloseOperation( EXIT_ON_CLOSE );

}

public static void main (String args[]) {

MyTest m = new MyTest();

}

}

Categories of GUI ClassesCategories of GUI Classes

Jcomponents: The base class for all Swing components except top-level containers (notice it is an abstract class)– some JComponents present information or interact with the user

Examples: labels (JLabel), buttons (JButton), text fields (JTextField)

– some JComponents are designed to hold other components, not present or interact, they are called Containers.

Examples: JPanel , JScrollPane Top Level Windows: are containers that are not contained by

any other containers; they can be iconified or dragged and interact with the native windowing system– Example: JFrame, JDialog (not JComponents at all)

Anatomy of a Anatomy of a JFrameJFrame

Look and Feel and platform dependent

Interacts with the window system

The contentPane is an inner container that holds your content

Swing Application TerminationSwing Application Termination

Any program that makes a Swing component visible, including a dialog created via JOptionPane, must explicitly exit by

1. calling System.exit( int code );

2. using setDefaultCloseOperation( EXIT_ON_CLOSE ); to tell Swing what to do when the window system attempts to close the window, (e.g. by clicking the window close box.)

Why? Because as soon as you put up a GUI window, you start a separate GUI thread that won't end when you run off the end of the main() method.

the windowclose box

Display the Greeting ApplicationDisplay the Greeting ApplicationTry 1, CritiqueTry 1, Critique

It’s too small and the colors don’t stand out. We need to choose a custom Font and text

(foreground) Color.

import java.awt.Font;import java.awt.Color;

FontsFonts

Standard constructor: Font myFont = new Font( String name, int style, int size ); Font name: safe approach is to use a logical font name, one

of– “Times New Roman”, "Serif", "Monospaced", "Dialog", "DialogInput", "Symbol"

Four font styles are present: Font.y where y is– PLAIN, BOLD, ITALIC, UNDERLINE– Font.BOLD + Font.ITALIC

Size is point size; 12 corresponds to standard printed text

ColorsColors

13 predefined colors: Color.x where x is– orange, pink, cyan, magenta, yellow, black, blue, white, gray, lightGray, darkGray, red, green

You can define your own colors// RGB or (red-green-blue)Color ugly= new Color(30, 90, 120);

Displaying the Greeting, Try 2Displaying the Greeting, Try 2

myFont = new Font( "Serif", Font.BOLD, 24 );myLabel.setFont( myFont );myLabel.setForeground( Color.red );myLabel.setBackground( Color.white );

Why doesn't the background change?Not all JComponents are opaque by default.

The JFrame crowds the label.

BordersBorders

In Swing, borders are objects. The best way to get some space around our label is to give

it an empty border. The best way to create a border is to use the factory

methods in class BorderFactory:import javax.swing.border.*;. . . Border empty = BorderFactory.createEmptyBorder( top,left, bottom,right);

Displaying the Greeting, Try 3Displaying the Greeting, Try 3

myLabel.setOpaque( true );Border empty = BorderFactory.createEmptyBorder(10,20,10,20);myLabel.setBorder( empty );myLabel.setHorizontalAlignment( SwingConstants.CENTER );

JLabel background is transparentin some look & feels by default

Add our emptyborder to thelabel and center it

Building GUI with ComponentsBuilding GUI with Components

As simple as our first application is, we can build some very interesting variations with little additional code.

JLabels can hold images as well as or instead of text.

A contentPane has 5 zones where you can add a component.

Complex ComponentsComplex Components

A JLabel is just about as simple as a component gets. But using a more complicated component is identical.

Components encapsulate their functionality spatially and conceptually.

Constructing GUIsConstructing GUIs

We will build the GUI by nesting simpler components into containers, and then combining the containers into larger containers.

JPanel is the workhorse of most complicated interfaces. It is– a good all purpose container– the standard drawing surface– a base class for many composite components

Layout Management, 1Layout Management, 1

Layout management is the process of determining the size and location of a container's components.

Java containers do not handle their own layout. They delegate that task to their layout manager, an instance of another class.

If you do not like a container's default layout manager, you can change it.

Container content = getContentPane(); content.setLayout( new FlowLayout() );

Layout Management, 2Layout Management, 2

Layout management is intrinsically recursive and proceeds top down in the containment hierarchy.

If a container encloses another container, the enclosing container can not position the inner container nor size itself until it knows how big the inner container needs to be.

Turning off Layout ManagementTurning off Layout Management

Although layout managers can introduce additional complexity, they are there for a very good reason.

The effect of layout management can be turned off by eliminating a container's layout manager via a call to setLayout(null).

The user must then explicitly lay out each component in absolute pixel coordinates through calls to setSize() and setLocation() or a single call to setBounds().

The problem with this strategy is that it lacks flexibility.

Greeting ApplicationGreeting Application Without Layout Management Without Layout Management

public MyTest( String dStr ) { . . . getContentPane().setLayout( null ); getContentPane().add( myLabel ); myLabel.setBounds( 50, 20, 250, 80 ); setSize( 350, 150 );}

CoordinatesCoordinates

Measured in pixels (e.g. 640 by 480, 1024 by 768, etc.) Upper left hand corner is origin (0,0) X axis goes from left to right, y from top to bottom Each component is anchored in its parent's coordinate system.

20

50

250

80

myLabel.setBounds( 50, 20, 250, 80 );setSize( 350, 150 );

3 Good Reasons to Use Layout 3 Good Reasons to Use Layout ManagementManagement

1. Often you do not know how large your application will be. Even if you call setSize(), the user can still physically resize the window of an application.

2. Java knows better than you how large components should be. It is hard to gauge the size of a JLabel, for instance, except by trial and error. And if you get the size correct on one system and then run it on another with a different set of fonts, the JLabel will not be correctly sized.

3. Once you lay out a GUI, you may want to make changes that will compromise a layout done by hand. If you use layout management, the new layout happens automatically, but if you are laying out the buttons by hand, you have an annoying task ahead of you.

Size MethodsSize Methods

Components communicate their layout needs to their enclosing container's layout manager via the methods: – public Dimension getMinimumSize() – public Dimension getPreferredSize() – public Dimension getMaximumSize()

There are three corresponding set methods that allow you to change a component's size hints. – public Dimension setMinimumSize( Dimension d )

Dimension d = new Dimension( int width, int height )

– public Dimension setPreferredSize( Dimension d ) – public Dimension setMaximumSize( Dimension d )

Size Methods, 2Size Methods, 2

Using these methods to change a component's size is far surer in general than using the explicit setSize() method.

The effect of a setSize() will only last until the Java environment lays the container out again.

Most components provide good default implementations for the get methods. For instance, a button sets its preferred size to accommodate its image and/or its label and font size.

When does Layout Occur?When does Layout Occur?

Swing will automatically (re)layout a GUI

1. when it first becomes visible,

2. when a component is added or deleted, or

3. when a component changes its size because the user physically changes its size (by resizing the window) or because the contents have changed (for instance, changing a label).

Layout ManagersLayout Managers

There are six layout manager classes supplied by Swing. They range from the simple FlowLayout to the flexible but at times frustrating GridBagLayout. Each manager class implements a particular layout policy.

Swing containers have default layout managers. A JFrame content pane uses BorderLayout and a JPanel uses FlowLayout.

FlowLayoutFlowLayout

The FlowLayout, the simplest of the managers, simply adds components left to right until it can fit no more within its container's width.

It then starts a second line of components, fills that, starts a third, etc.

Each line is centered within the enclosing container. FlowLayout respects each component's preferred size

and will use it to override a size set by setSize().

FlowLayout Example, 1FlowLayout Example, 1

public class Flow extends JFrame { private Font labelFont; private Border labelBorder; public Flow( ) { setDefaultCloseOperation( EXIT_ON_CLOSE ); labelFont = new Font( "SansSerif",Font.BOLD,24 ); labelBorder = BorderFactory.createLineBorder(Color.red,1); getContentPane().setLayout( new FlowLayout() ); setSize(200, 200 ); }

FlowLayout Example, 2FlowLayout Example, 2 public void addLabel( String labelStr ) { JLabel label = new JLabel( labelStr ); label.setFont( labelFont ); label.setBorder( labelBorder ); getContentPane().add( label ); } public static void main (String args[]) { Flow flow = new Flow(); flow.addLabel( “Hello1" );

flow.addLabel( “Hello2" ); . . .

flow.addLabel( “Hello10" ); flow.setVisible( true ); }}

BorderLayout ZonesBorderLayout Zones

North

South

West EastCenter

BorderLayout PolicyBorderLayout Policy

You specify the zone via a second String argument in the add() method. For example, the following line of code adds the button labeled “DoIt" to the middle of a container.

add( new JButton( “DoIt" ), "Center" );// "Center" == BorderLayout.CENTER

A BorderLayout may horizontally stretch its North and South components (if they exist), vertically stretch its East and West components, and stretch the Center component both ways to accommodate its container's size and the constraints of its other four sectors.

This can be useful. If you put a JPanel in the Center zone of a container managed by a BorderLayout, the manager will always resize the JPanel to take up all extra space, which is usually what you want if you are using it as a drawing surface.

Grid LayoutGrid Layout

The GridLayout class is a layout manager that lays out a container's components in a rectangular grid.

The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

In the normal constructor you specify the number of rows or columns but not both. The one that is not zero has a fixed number of elements; the other grows as you add components.

getContentPane().setLayout( new GridLayout(0,2));

would set a JFrame's layout to a two column grid. The number of rows would depend on the number of added components.

ExercisesExercises1. Create a Swing application with a button saying “click me”.2. Create a Swing application with a label saying “Sawa Sawa”,

and a button saying “Karibu”. Put the button at the center of the frame, and the label at the bottom of the frame. (hint: use border layout)

3. Create a Swing application with: 1) two red color labels, font size 14, bold, your favorite font style. One label saying “mimi”, the other saying “wewe”; 2) a button (green foreground color, black background), saying “kucheza”;3) add two labels in a JPanel, using flow layout,4) add the JPanel object (center) and the button (north) to the contentPane, using border layout

top related