Sie sind auf Seite 1von 30

Advanced Programming

Chapter 1 – 1
Java AWT and Swing

1
Contents
 Concepts of AWT and Swing
 Frame, label, Button, TextField, ComboBox,…
 JFrame, JLabel, JButton, JtextField, JComboBox,…

2
Abstract Window Toolkit (AWT)
• The Abstract Window Toolkit (AWT) is a GUI toolkit designed to work
across multiple platforms.
• Event-driven: the window is displayed, and when things happen, an
event handler is called. Generally, the default event handler is to do
nothing.
• A graphical user interface is built of graphical elements called
components.
• Typical components include items such as buttons, scrollbars, and text
fields.
• Components allow the user to interact with the program and provide the
user with visual feedback about the state of the program.
• Must import java.awt.* and java.awt.event.*

3
General Layout of AWT

Swing

4
What are Components?
• A component is an object having a graphical representation that can be
displayed on the screen like checkboxes, menus, windows, buttons, text
fields, applets, and more.
• A container is a special component that can hold other components like
panels, windows, applets, frames.
• Functionality of most GUI components derive from the Component
and Container classes.
• Represents something that has a position and a size and can be painted
on the screen as well as receive input events.
• This is an abstract class and may not be instantiated.
Some important methods:
• public void paint(Graphics g);
• public void show( );
• public void addComponentListener(ComponentListener l )
• Various routines to set fonts, handle mouse events, etc.

5
Top Level Windows
• Window: A top-level window that has no border.

• Frame: A top-level window that has a border and can also have an
associated MenuBar.

• Dialog: A top-level window used to create dialogs. One subclass of this


is the FileDialog.

• Panel: Subclass of container used inside other containers.

• Used to store collections of objects.

• Does not create a separate window of its own.

6
Important I/O Components
• Button: A push button.
• Canvas: General-purpose component that lets you paint or trap input
events from the user. It can be used to create graphics.
• Checkbox: A component that has an "on" or "off" state. You can place
Checkboxes in a group that allows at most 1 box to be checked.
• Choice: A component that allows the selection of one of a group of
choices. Takes up little screen space.
• Label: A component that displays a static string at a certain location.
• List: A scrolling list of strings. Allows one or several items to be
selected.
• TextArea: Multiple line text components that allows viewing and
editing.
• TextField: A single-line text component that can be used to build forms.

7
Where to declare components
• Components are typically declared in one of several places:

• Field variables: Some components should be declared as field variables


(instance variables, member variables).
• This is the appropriate place to declare components which must be referenced after
the interface is constructed. Typically these are text fields or text areas, check boxes,
etc.

• Local variables: Local variables should be used for components which


are never referenced after the interface is constructed.
• Typically these are panels for holding components, buttons (whose interaction is thru
their listeners), ...

• Anonymous: Anonymous creation is typical with labels, which can be


created and added in one step and never assigned to a variable.

8
Eg1:
import java.awt.*;
public class Hello extends Frame {
private Label text;
public Hello() // constructor
{
// create a label containing "Hello World!", with the text
centered
text = new Label("Hello World!", Label.CENTER);

// add the label to the Frame


add(text);

// set the size of the frame and make it visible


setSize( 300, 100 );
setVisible( true );
}
// main
public static void main( String[] args ) {
new Hello();
}
}
9
Eg2
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
public class Trials2 {
static Button b = new Button("Click me");//button object
public static void main(String[] a){
Frame f = new Frame();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0); //close the window
}
});
Trials2 t = new Trials2(); //class constructor
b.addActionListener(t.new MyListener());

f.add(b);
f.pack();
f.setVisible(true);
}
public class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "you clicked me "); //from Swing
}
}
} 10
Eg3: Frame f = new Frame();
f.addWindowListener(new
import java.awt.*; WindowAdapter(){
public void windowClosing(WindowEvent we)
import java.awt.event.*; {
public class GUI3 System.exit(0); //close the window
{ }
static TextField tf = new TextField(12); });
static int count = 0; Panel p = new Panel();
p.setLayout(new FlowLayout());
public static void main(String[] args) { p.add(but); p.add(tf);
Button but = new Button("Press Me"); f.add(p);
but.addActionListener(new f.pack();
ActionListener() { f.setVisible(true);
public void }
actionPerformed(ActionEvent ev) { }
count++;
tf.setText("clicked " + count);
}
});

11
12
WHAT IS SWING?
• Swing is Java's GUI(graphical user interface) library
• Swing is created to provide a more sophisticated set of GUI components than
the Abstract Windows Toolkit (AWT)
• You MUST import the following packages to use swing:
import javax.swing.*;
• Java Swing consists of:
– Pluggable Look and feel – means each picture shows the same program but with a
different look and feel

– Accessibility API - Screen readers, Braille displays, ...

– Java 2D

– Drag and Drop - Between Java applications and native applications

• javax.swing and java.awt together offer a complete API for Java applications to
operate graphical devices and create GUI.
13
WHAT IS SWING?
The Swing package contains following sub packages:
• javax.swing - Provides a set of "lightweight“ components that, to the
maximum degree possible, work the same on all platforms.
• javax.swing.border - Provides classes and interfaces for drawing specialized
borders around a Swing component.
• javax.swing.colorchooser - Contains classes and interfaces used by the
JColorChooser component.
• javax.swing.event - Provides support for events fired by Swing components.
• javax.swing.filechooser - Contains classes and interfaces used by the
JFileChooser component.
• javax.swing.plaf - Provides one interface and many abstract classes that
Swing uses to provide its pluggable look and feel capabilities.
• javax.swing.plaf.basic - Provides user interface objects built according to the
Basic look and feel.

14
WHAT IS SWING?
• javax.swing.plaf.metal - Provides user interface objects built according to the
Java look and feel (once codenamed Metal), which is the default look and feel.
• javax.swing.plaf.multi - Provides user interface objects that combine two or
more look and feels.
• javax.swing.plaf.synth - Provides user interface objects for a skinnable look and
feel in which all painting is delegated.
• javax.swing.table - Provides classes and interfaces for dealing with JTable.
• javax.swing.text - Provides classes and interfaces that deal with editable and
non-editable text components.
• javax.swing.text.html - Provides the class HTMLEditorKit and supporting
classes for creating HTML text editors.
• javax.swing.text.html.parser - Provides the default HTML parser, along with
support classes.
• javax.swing.text.rtf - Provides a class (RTFEditorKit) for creating Rich Text
Format text editors.
• javax.swing.tree - Provides classes and interfaces for dealing with JTree.
• javax.swing.undo - Allows developers to provide support for undo/redo in
applications such as text editors.

15
Why Swing?
• Better, more flexible GUIs.
• Faster. Uses “lightweight components”
• Easy scrolling
• Easy tooltips
• Mnemonics
• General attempt to compete with MFC
• Can set custom look-and-feel

16
Swing Components
• Usually start with ‘J’:
• All components are lightweight (written in Java) except:
– Japplet
– Jframe
– Jwindow
– Jdialog
• AWT components have Swing analogs
AWT to Swing Mappings
• Almost all map by prepending a ‘J’
Examples:
– Button -> Jbutton
– Panel -> Jpanel
– List -> Jlist
Exceptions:
– Checkbox -> JCheckBox (note case change)
– Choice -> JComboBox
17
Some New Components
• Jtree
– Creates a tree, whose nodes can be expanded.
• Jtable
– Used to display tables (for instance, those obtained from databases)
• Tooltips
– Use setToolTipText to install a tooltip.
– Works for any JComponent.
Jbutton b = new Jbutton( "Quit" );
b.setToolTipText("Press to quit");
• JPopupMenu
– Appears when you right-click on a component
• JOptionPane
– Contains static methods that pop up a modal dialog.
– Commonly used methods are:
showMessageDialog( )
showConfirmDialog( )
showInputDialog( )
18
• Borders
– Use setBorder to set borders for a JComponent.
– Available borders include
• TitledBorder
• EtchedBorder
• LineBorder
• MatteBorder
• BevelBorder
• SoftBevelBorder
• CompoundBorder
– In package javax.swing.border

19
• Sliders
– Sliders are implemented with the Jslider class.
– Important methods:
JSlider( int orient, int low, int high, int val );
void setValue( int val );
int getValue( );
void setPaintTicks( boolean makeTicks );
void setMajorTickSpacing( int n );
void setMinorTickSpacing( int n );
ChangeListener interface handles slider
events. Must implement stateChanged
method.
– Note: this interface is in package javax.swing.event.

20
• Progress Bars
– JProgressBar displays data in relative fashion from empty (default
value=0) to full (default value=100).
– Interesting methods
double getPercentComplete( );
int getValue( );
void setValue( int val );
• Scrolling
– Use a JScrollPane to wrap any Component.
– Scrolling will be automatically done.
– Example:
JPanel p = new JPanel( );
JList list = new JList( );
for( int i = 0; i < 100; i++ )
list.addItem( "" + i );
p.add( new JScrollPane( list ) );
21
• Other Stuff (There's Lots)
– JFileChooser: supports file selection
– JPasswordField: hides input
– HTML-aware: Can do simple HTML formatting and display
– JTextPane: text editor that supports formatting, images, word
wrap
– …
Implementing a Swing GUI
– Import javax.swing.*, java.io.*, java.awt.*
– Make a specific class to do GUI functions
– Specify all the GUI functions/components in the class’s constructor
(or methods / classes called by the constructor)
– Run the GUI by instantiating the class in the class’s main method
22
Anatomy of an Application GUI
GUI Internal structure

JFrame JFrame

JPanel
containers

JPanel
JButton

JButton JLabel
JLabel

23
Anatomy of a JFrame
title bar

minimize
maximize
close

The contentPane holds your


content; created automatically
when a JFrame is created

24
Eg1:
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
// let’s create a frame object and give some title
JFrame frame = new JFrame("HelloWorldSwing");
// let’s have a label
JLabel label = new JLabel("Hello World");
//let’s add the label to the frame we have created above
frame.getContentPane().add(label);
//this is the operation to do when the window is closed.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//pack() causes a window to be sized to fit the preferred
//size and layouts of its sub-components
frame.pack();
// let’s make the frame to be visible
frame.setVisible(true);
}
}
25
Eg2
public class Trials {
static JButton b = new JButton("Click me");
public static void main(String[] a){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Trials t = new Trials();
b.addActionListener(t.new MyListener());

f.add(b);
f.pack();
f.setVisible(true);
}
public class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "you clicked me ");
}
}
}

26
Eg3: JFrame f = new JFrame();
import javax.swing.*;
import java.awt.*; f.setDefaultCloseOperation(JFrame.EXIT_
import javax.swing.event.*; ON_CLOSE);
import java.awt.event.*; JPanel p = new JPanel();
public class GUI2 p.setLayout(new FlowLayout());
{ p.add(but); p.add(tf);
static JTextField tf = new JTextField(12); f.add(p);
static int count = 0; f.pack();
public static void main(String[] args) { f.setVisible(true);
JButton but = new JButton("Press Me"); }
but.addActionListener(new
ActionListener() { }
public void
actionPerformed(ActionEvent ev) {
count++;
tf.setText("clicked " + count);
}
});
27
Swing Vs. AWT
• Concepts are all the same.
• AWT is more portable Swing is better looking
• AWT lays out inconsistently on different OSs)
• Most old AWT is easily translated: Add J in front of the class names
• AWT Uses peer components of the OS; heavyweight components
• Swing has easy-to-use new stuff including tooltips, mnemonics, borders,
JOptionPane.
• Swing 99% java; lightweight components
• Swing lays out consistently on all OSs
• Swing uses AWT event handling
• Unlike AWT components, Swing components are not implemented by
platform-specific code. Instead they are written entirely in Java and
therefore are platform-independent. The term "lightweight" is used to
describe such an element.
28
Swing Vs. AWT
• Swing provides replacements for most of the AWT components, although
many AWT non-component classes remain in use.
• Upward compatibility is assured in almost all cases; an AWT continues to
work in Java.
• Mixing both Swing and AWT components in the same interface can
produce errors, so one has to make a decision about which to use.
• Swing advantages
• Swing is faster.
• Swing is more complete.
• Swing is being actively improved.
• AWT advantages
• AWT is supported on older, as well as newer, browsers so Applets
written in AWT will run on more browsers.
• The Java Micro-Edition, which is used for phones, TV settop boxes,
PDAs, etc, uses AWT, not Swing.

29
What Is Layout?
• A layout is a set of rules that defines how graphical components should be
positioned in a container.
• Layouts tell Java where to put components in containers.
• Every panel (and other container) has a default layout.
• Each layout has its own way to resize components to fit the layout.
There two ways to position a component in a container:
1. Using a predefined layout and allowing the layout to decide where to
position the component.
• This is a soft way of positioning a component. If the container changes its size, the
component's position will be adjusted.
• But you may not able to get precisely where you want to component to be.
2. Specifying the position of the component using the container's
coordinates.
• This is a hard way of positioning a component.
• You can get precisely where you want the component to be. But if the container
changes its size, the component's position will not be adjusted.

30

Das könnte Ihnen auch gefallen