Java Swing and Awt
Java Swing and Awt
GUIs are built from GUI components. These are sometimes called
controls or widgets.
Maps general Java code to each operating system's real GUI system.
Problems
AWT components depend on native code counterparts to handle their
functionality. Thus, these components are often called heavyweight
components.
AWT cont...
• Pros
− Portability: Pure Java implementation.
− Features: Not limited by native components.
− Look and Feel: Pluggable look and feel. Components automatically
have the look and feel of the OS they are running on.
• Cons
‒ Performance: Swing components handle their own painting (instead of
using APIs like DirectX on Windows).
‒ Look and Feel: May look slightly different than native components.
AWT: Pros and Cons
• Pros
‒ Speed: native components speed performance.
‒ Look and feel: AWT components more closely reflect the look and feel
of the OS they run on.
• Cons
‒ Portability: use of native peers(OS component) creates platform
specific limitations.
Components (Swing)
Components cont..
‒ Component is an abstract class that encapsulates all of the attributes of
a visual component.
‒ All user interface elements that are displayed on the screen and that
interact with the user are subclasses of Component.
Containers
‒ Two Containers
Window
Frame
dialog
panel
Containers cont..
java.lang.Object java.awt.Component
java.awt.Container
javax.swing.JComponent
java.awt.Window
javax.swing.JPanel
javax.swing.JFileChooser
java.awt.Frame
javax.swing.JPopupMenu
javax.swing.JToolbar
javax.swing.JFrame
javax.swing.JLabel
Containers cont..
‒ Every container has a LayoutManager that determines how different components are
positioned within the container.
‒ Since each Panel can have its own LayoutManager, you can do many
things with panels that you can't do with a single LayoutManager.
‒ Panel is a window that does not contain a title bar, menu bar, or border.
finally add this panel to the default one by using add() method. i.e
add(panelName);
It can be moved.
Its purpose is to get some particular information from the user (input) or to
impart some particularly important information to the user (output).
It is normally visible on the screen only until it gets the input or receives
acknowledgement from the user about its output.
Windows cont..
‒ Frames let you separate different functions or data into different windows.
‒ Everything you need to create and work with frames is contained in the java.awt.Frame
class.
‒ To create a new frame without a title bar use the Frame() constructor with no arguments.
f.add(new Label(“frame”),BorderLayout.CENTER);
‒ The size and position of any given frame is unpredictable unless you specify it.
‒ Specifying the size is easy. Just call the frame's setSize() method like this
f.setSize(150,150);
‒ You move a Frame with the setLocation(int x, int y) method.
However x and y are relative to the screen
Frame cont..
‒ When you're done adding components, resizing and moving the Frame, make it
visible by calling its show() method like so:
Frame f=new Frame(“this is frame title”);
f.show();
or f.setVisible(true); //since it inherits from java.awt.Component
Frame Example
import java.awt.*;
public class FrameTester {
public static void main(String[] args) {
Frame myFrame = new Frame("My AWT Frame");
myFrame.setSize(250, 250);
myFrame.setLocation(300,200);
myFrame.add("Center", new Label(“Hello awt”));
myFrame.show();
}}
This window cannot be closed because it does not yet respond to the
WINDOW_CLOSING event.
Frame Example2
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);
}
}
‒ JFrames (and Swing containers in general) differ from AWT frames (and AWT containers in
general) in that you must add component's to the JFrame's content pane rather than directly
to the frame itself. Furthermore JFrames are closeable by default whereas AWT frames are
not.
Centering a frame on screen
import java.awt.*;
public class CenteredFrameTester {
public static void main(String[] args) {
Frame myFrame = new Frame("My Frame");
myFrame.setSize(250, 250);
Toolkit kit = myFrame.getToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
Dimension windowSize = myFrame.getSize();
int windowWidth = windowSize.width;
int windowHeight = windowSize.height;
int upperLeftX = (screenWidth - windowWidth)/2;
int upperLeftY = (screenHeight - windowHeight)/2;
myFrame.setLocation(upperLeftX, upperLeftY);
myFrame.show();
} }
Main Steps in GUI Programming
‒ To make any graphic program work we must be able to create windows and add
content to them.
‒ Dialogs are more transitory. They're used for simple user input or for quick alerts to the
user.
‒ java.awt.Dialog is a subclass of java.awt.Window and hence of java.awt.Container and
java.awt.Component.
‒ Therefore a lot of what you learned about frames applies to dialogs as well. You move
them, resize them and add to them almost exactly as you do for frames.
‒ There are two differences between dialogs and frames:
‒ A modal dialog blocks all other use of the application until the user
responds to it.
‒ A modal dialog cannot be moved and does not allow the user to switch to
another window in the same program.
On some platforms the user may not even be able to switch to another
program
‒ Non-modal dialogs pop-up but they don't prevent the user from doing other
things while they're visible.
‒ Because modal dialogs inconvenience users by forcing them to respond
Dialogs cont..
‒ The only methods that are significantly different between a dialog and a frame are the
constructors.
‒ There are two constructors for Dialog which differ in whether or not the dialog is given a
title.
d.setResizable(true);
‒ You can give a dialog a title bar by adding the title string to the constructor:
‒ create your own dialog by extending it to Dialog class and instantiate that
subclass from the main program.
‒ For example one of the simpler common dialogs is a notification dialog that
gives the user a message to which they can say OK to signify that they've
read it. The next slide describes Dialog subclass.
Dialog subclass Example
‒ All of the components that we have shown so far have been positioned
by the default layout manager.
‒ It is possible to lay out Java controls by hand, too, you generally won’t
want to, for two main reasons.
First, it is very tedious to manually layout a large number of
components.
Second, sometimes the width and height information is not yet
available when you need to arrange some control, because the
native toolkit components haven’t been realized.
Layout Manager cont..
‒ Flow Layout
‒ Grid Layout
‒ Border Layout
‒ GridBag Layout
‒ Card Layout
‒ Box Layout
Flow Layout
‒ FlowLayout is the default layout manager for panels.
‒ In all cases, when a line is filled, layout advances to the next line.
Flow Layout
‒ Here are the constructors for FlowLayout:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
‒ Instantiate it this way
FlowLayout() flow=new FlowLayout();
flow.setAlignment(FlowLayout.CENTER);// in place of center you can also
use RIGHT,LEFT,LEADING AND TRAILING
flow.setHgap(5); // to set horizontal space between controls
flow.setVgap(10); // to set vertical space between controls
Flow Layout
‒ FlowLayout(int how) use it this way
public BorderLayout()
myFrame.setLayout(new BorderLayout());
myFrame.add(new JButton("Button 1"), BorderLayout.NORTH);
GridLayout(intnumRows, intnumColumns)
Use it as GridLayout grid=new GridLayout(3,3);
GridLayout(intnumRows, intnumColumns, inthorz, intvert)
Use it as GridLayout(3,3,10,5);
Finally add to SetLayout, using setLayout(grid);
Remember if want to add Layout to layout manager you can do it
as:
setLayout(new GridLayout(2,3,2,4)); // the same for flow and border
layout
Card Layout
‒ The CardLayout class is unique among the other layout managers in that it stores
several different layouts. Each layout can be thought of as being on a separate
index card in a deck that can be shuffled so that any card is on top at a given time.
‒ This can be useful for user interfaces with optional components that can be
dynamically enabled and disabled upon user input. CardLayout provides these
two constructors:
CardLayout( )
‒ Use of a card layout requires a bit more work than the other layouts. The
cards are typically held in an object of type Panel.
‒ This panel must have CardLayout selected as its layout manager. The
cards that form the deck are also typically objects of type Panel.
‒ Thus, you must create a panel that contains the deck and a panel for each
card in the deck. Next, you add to the appropriate panel the components
that form each card. Finally, you add this panel to the window.
Card Layout cont..
‒ When card panels are added to a panel, they are usually given a name. Thus,
most of the time, you will use this form of add( ) when adding cards to a panel:
void add(ComponentpanelObj, Objectname)
Eg. Panel p=new Panel();
CardLayout c=new CardLayout(5,10);
p.setLayout(c);
Panel p1=new Panel();
Panel p2=new Panel();
p.add(p1,”Panel 1”);
p.add(p2,”Panel 2”);
add(p);
Card Layout cont..
‒ After you have created a deck, your program activates a card by calling
one of the following methods defined by CardLayout:
void first(Container deck)
‒ Here deck is a reference to the container (usually a panel) that holds the
cards, and cardName is the name of a card. Calling first( )causes the first
card in the deck to be shown.
‒ To show the last card, call last( ). The same for previous and next card. Both
next( )and previous( )automatically cycle back to the top or bottom of the
deck, respectively. The show( )method displays the card whose name is
passed in cardName.
Components
Components
Label( )
Label(Stringstr)
Label(Stringstr, inthow)
JLabel cont..
‒ The first version creates a blank label. The second version creates a label
‒ The third version creates a label that contains the string specified by str using
the alignment specified by how. The value of how must be one of these three
‒ We can set or change the text in a label by using the setText( ) method.
Button( )
Button(String str)
JButton cont..
import java.awt.*;
import javax.swing.*;
frame.setVisible(true);
}
}
JButton cont..
Handling Buttons
‒ Each time a button is pressed, an action event is generated. This is sent to any
‒ Each listener implements the ActionListener interface. That interface defines the
reference to the button that generated the event and a reference to the action
‒ You can Add ActionListener to Button using the following ways as well.
• Import java.awt.event.ActionListener;
// import other class here us you program
• Public class ButtonDemo extends Applet {
• Button button;
• //other declaration here;
• Public void ButtonDemo(){
button =new Button(“Demo”);
add(button);
button.addActionListener(new ActionListener(){
• Public void actionPerformed(ActionEvent a){
• If(a.getSource()==button){ // what ever you want here }
Or if(a.getActionCommand().equals(“Demo”)){
}}}); //
}}
JButton cont..
a.getActionCommand().equals(“button”);
‒ Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and
TextField( )
TextField(intnumChars)
TextField(Stringstr)
TextField(Stringstr, intnumChars)
TextField
be displayed
someComponent.addActionListener(instanceOfMyClass);
3. providing code that implements the methods in the listener interface in the
the action...
How to Implement an Event Handler
1
public class ButtonClickExample extends JFrame implements ActionListener {
public ButtonClickExample() {
b.addActionListener(this); 2
getContentPane().add(b);
pack();
setVisible(true);
} 3
public void actionPerformed(ActionEvent e) {
b.setBackground(Color.CYAN);
new ButtonClickExample();
Text Field Event Handler
‒ Since text fields perform their own editing functions, your program
generally will not respond to individual key events that occur within a
text field. However, you may want to respond when the user presses
‒ Sometimes a single line of text input is not enough for a given task. To
handle these situations, the AWT includes a simple multiline editor called
TextArea(String str, intnumLines, int numChars, int sBars) // int sBars type of
‒ Most of the methods are similar to TextField but there is some new feature
‒ You change the state of a check box by clicking on it. Check boxes can be used
individually or as part of a group. Check boxes are objects of the Checkbox class.
Checkbox( )
Checkbox(String str)
check.setCheckboxGroup(cbGroupName);
‒ Each time a check box is selected or deselected, an item event is generated. We can add
Item event to checkbox by implementing the ItemListener interface. That interface defines
the itemStateChanged( )method, with argument ItemEvent object.
‒ To execute any activities depending on checkbox state use getState() method. Like below:
If(check.getState()==true/false){
}
CheckboxGroup
‒ It is possible to create a set of mutually exclusive check boxes in which one and only one check
box in the group can be checked at any one time. These check boxes are often called radio
buttons.
‒ You can determine which check box in a group is currently selected by calling
getSelectedCheckbox(). You can set a check box by calling setSelectedCheckbox().
combobox.add(“first”);
combobox.add(“second”);
‒ To determine which item is currently selected, you may call either getSelectedItem() or
getSelectedIndex().
‒ The getSelectedItem( )method returns a string containing the name of the item.
Choice cont…
int getItemCount( ) // return number of item found in choice
combobox.getItemCount(); // return 2
inside itemStateChanged() method or inside other applet method use this statements
Or if (combobox .getItem(combobox.getSelectedIndex())==second){
}
List
‒ The List class provides a compact, multiple-choice, scrolling selection list. Unlike the
Choice object, which shows only the single selected item in the menu, a List object can
be constructed to show any number of choices in the visible window. List provides these
constructors:
List( )
‒ To add item to List use add(string str) or add(string str, int index) methods.
‒ you can determine which item is currently selected by calling either getSelectedItem( )or
getSelectedIndex( ) for single selection.
List cont…
‒ you can determine which item is currently selected by calling either
getSelectedItems( )or getSelectedIndexes( ) for multiple selection.
java.awt.event.ComponentListener
java.awt.event.ContainerListener
java.awt.event.FocusListener
java.awt.event.KeyListener
java.awt.event.MouseListener
java.awt.event.MouseMotionListener
java.awt.event.WindowListener
java.awt.event.ActionListener
java.awt.event.AdjustmentListener
Mouse Events
A java.awt.event.MouseEvent is sent to a component when the mouse state changes over the
component.
There are seven types of mouse events, each represented by an integer constant:
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter
Adapter Classes
‒ Therefore, MouseAdapter can be written as:
package java.awt.event;
import java.awt.*;
import java.awt.event.*;
public class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent evt) {}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}}
import java.awt.*;
import java.awt.event.*;
public class MouseBeeper extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
Toolkit.getDefaultToolkit().beep();
// No need to write other left unimplemented method of mouselisetner
interface. Since MouseAdapter class does the job.
}
}
Menu
‒ Menus are composed of three hierarchical pieces.
MenuBar, Menu and MenuItem
‒ The menu bar contains the various menus.
Each menu bar contains one or more menus. Menus are organized topically.
‒ Each menu contains one or more menu items.
‒ The menu items are the individual actions such as Open, Print, Cut or Copy.
They are not shown except when the menu is active.
‒ No more than one menu will be active at a time.
Menu Classes
‒ The AWT contains four main classes to handle menus:
java.awt.Menu
java.awt.MenuBar
java.awt.MenuItem
java.awt.PopupMenu
‒ To use menus in your application you need to add instances of all three
classes,
one MenuBar with one or more Menus, each with several MenuItems.
Menu Classes
‒ The java.awt.MenuComponent class is the ultimate superclass of all
these classes.
• MenuComponent extends java.lang.Object.
‒ Thus menus, menu bars, and menu items are not components and
cannot be added to containers in the usual fashion.
‒ Both MenuBar and MenuItem extend MenuComponent.
‒ Menu extends MenuItem.
‒ Furthermore, MenuBar implements the java.awt.MenuContainer
interface.
Menu Classes
‒ Swing contains three main classes to handle menus:
javax.swing.JMenu
javax.swing.JMenuBar
javax.swing.JMenuItem
javax.swing.JCheckboxMenuItem
javax.swing.JRadioButtonMenuItem
‒ MenuBar implements the java.awt.MenuContainer interface.
Steps to Create Menu
‒ You should build the menus before you display them. The typical order is:
MenuItems:
editMenu.add(undo);
editMenu.addSeparator();
editMenu.add(cut);
editMenu.add(copy);
‒ The addSeparator() method adds a horizontal line across the menu. It's used to separate logically separate functions in one menu.
Create Menu
‒ Once you've created the Menus, you add them to the MenuBar using the MenuBar's add(Menu m) method like
this:
myMenubar.add(fileMenu);
myMenubar.add(editMenu);
‒ Finally when the MenuBar is fully loaded, you add the Menu to a Frame using the frame's setMenuBar(MenuBar
mb) method.
Given a Frame f:
f.setMenuBar(myMenuBar);
editMenu.add(copy);