FP612 FP612 WEB PROGRAMMING 2 WEB PROGRAMMING 2
Abstract Window Toolkit (AWT) is a set of application program interfaces ( API s) used by Java programmers to create graphical user interface ( GUI ) objects, such as buttons, scroll bars, and windows.
In Java, the AWT API is a package (java.awt) that contains classes from which GUIs are built import java.awt.*;
Consist s of a set of APIs that support: The creation of Graphical User Interface
components such as buttons, labels, checkboxes, scrollbars, menus and etc.
Event-handling that manages the events fired by some GUI components.
Graphics and imaging tools. Layout managers for handling the layouts
of components on windows independent of window size and screen resolution.
AWTEvent
Font
FontMetrics
Component
Graphics
Object Color
Canvas
Button
TextComponent
Label
List
CheckBoxGroup
CheckBox
Choice
Container Panel Applet
Frame
Dialog FileDialog
Window
TextField
TextArea
MenuComponent MenuItem
MenuBar
Menu
Scrollbar
LayoutManager
Container Description
Container The parent of all classes that can contain other components.
Panel A container used to organize and group components. It is added to another containers
Applet A panel that is displayed in a web browser
Window A window is free floating window on the display that is independent of other containers. Two types of window: Frame and Dialog
Frame A window that has a border and a title bar. It supports the use of menu.
Dialog A popup window is created to deal with a specific situation and cannot have a menu bar.
Container is an abstract subclass of Component, which allows other components to be nested inside it.
Containers are helpful in arranging GUI components on the screen.
Example of container is: Panel Window Applet Frame Dialog
A frame is a subclass of Window.
It is a window with title and resize corners.
Frame is a window that is not contained inside another window.
Frame is the basis to contain other user interface components in Java GUI applications.
Panel like Frames, provide the space to attach any GUI component, including other panels.
Panel is invisible container.Once a Panel object is created, it
must be added to a window or Frame object in order to be visible.
A dialog is popup window or message box normally used as a temporary window to receive additional information from the user, or to provide notification that some event has occurred.
A dialog can be either modeless (the default) or modal.
Applet is a container that contain program written in the Java programming language that can be run from a web browser or an applet viewer.
A window must have either a frame, dialog, when it's constructed.
invisible
Window w = new Window( Window owner,GraphicsConfiguration gc); Rectangle bounds = gc.getBounds(); w.setLocation(10 + bounds.x, 10 + bounds.y);
import java.awt.Button; public class PackageTest { /* …….*/}
import java.awt.*; public class
PackageTest { /* …….*/}
or
In this class, you learnt the following:
AWT – is a Java package containing standard Graphical User Interface (GUI) elements, drawing primitives, event-handling mechanisms, windows, dialogs, components, layout managers, interfaces
Container is a class that is used to contain other java objects – panel, window, applet, frame and dialog.
By the end of the class, student should be able to: Define the use of Frame in Java
programs Create and set the Frame windows Create menu bars in Java programs Write a program with dialog and panels
import java.awt.*; public class MyFrame {
public static void main(String[] arg) {MyFrame bingkai= new
MyFrame("FrameDemo"); bingkai.setSize(200,100); bingkai.setVisible(true);
}}
setSize (width, height):This is the method of the Frame class that sets the size of the frame or window. This method takes two arguments width (int), height (int).
setVisible(boolean):This is also a method of the Frame class sets the visibility of the frame. The frame will be invisible if you pass the boolean value false otherwise frame will be visible.
Are used to group a number of components A panel cannot be seen directly(do not have
border), we need to add it to a frame
Create a panel.Panel p = new Panel();
Add components to panel.p.add(label1);
Add panel to container.add(p, BorderLayout.CENTER);
By the end of the class, student should be able to: Define swing component and identify its
uses. List the swing packages:
▪ javax.swing▪ javax.swing.border▪ javax.swing.event
An enhanced GUI component set – tree view, tabbed panes
Swing components are lightweight - Written in Java, not weighed down by complex GUI capabilities of platform
Defined in package javax.swing
Swing components allow programmer to specify look and feel (LAF) Can change depending on platform Can be the same across all platforms
.
JButton
JMenuItem
JCheckBoxMenuItem
AbstractButton
JComponent
JMenu
.JRadioButtonMenuItem
.JToggleButton JCheckBox
JRadioButton
.JComboBox
.JInternalFrame .JLayeredPane
.JList .JMenuBar .JOptionPane
.JPopupMenu
.JProgressBar
.JPane
.JFileChooser .JScrollBar .JScrollPane
.JSeparator
.JSplitPane
.JSlider .JTabbedPane
.JTable
.JTableHeader
.JTextField .JTextComponent
.JEditorPane
.JTextArea
.JToolBar
.JToolTip
.JTree
.JRootPane
.JPanel
.JPasswordField
.JColorChooser
.JLabel
Package Name
Purpose
javax.swing Provide a set of lightweight components such as JButton, JLabel and much more
javax.swing.border
Provides classes and interfaces for drawing specialized borders such as bevel, etched, line and more
javax.swing.event Dealing with events generated by some Java Swing GUI component
javax.swing.colorchooser javax.swing.filechooser javax.swing.table javax.swing.undo javax.swing.tree javax.swing.plaf javax.swing.text javax.swing.plaf.basic javax.swing.text.html javax.swing.plaf.metal javax.swing.text.html.parser javax.swing.plaf.multi javax.swing.text.rtf javax.swing.plaf.synth
JFrame construct a new frame
JLabel display area for a short text, an image, or both
JButton component that triggers an action event when clicked
JCheckBox component that enables the user to toggle a choice on or off, like a light switch.
JRadioButton
used in the group, where only one button is checked at a time.
JScrollPane component that supports automatically scrolling without coding.
JTextField input area where the user can type in characters.
JTextArea enables the user to enter multiple lines of text.
import javax.swing.JFrame; // import javax.swing.*;public class Frame2 extends JFrame{
public Frame2() { setTitle("Test Frame");//super ("Test Frame"); setSize(400, 200); setVisible(true); }
public static void main(String[] args) { Frame2 a = new Frame2();
a.setDefaultCloseOperation(EXIT_ON_CLOSE);}
}
JLabel(String text,int horizontalAlignment)
JLabel lblName = new Jlabel(“Name”,SwingConstants.LEFT)
JLabel(String text)
JLabel lblName = new JLabel(“Name”)
JLabel(Icon icon, int horizontalAlignment)
Icon cat = new ImageIcon(“cat1.gif");JLabel lblOnel = new JLabel("Label with text and icon", cat, SwingConstants.LEFT)
import java.awt.*;import javax.swing.*; public class LabelTest extends JFrame {private JLabel label1; // set up GUIpublic LabelTest(){
super( "Testing JLabel" );// get content pane and set its layoutContainer container = getContentPane();container.setLayout( new FlowLayout() );// JLabel constructor with a string argumentlabel1 = new JLabel( "Label with text" ); label1.setToolTipText( "This is label1" ); container.add( label1 );
setSize( 275, 170 );setVisible( true );
} // end constructor
public static void main( String args[] ) { LabelTest application = new LabelTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }}
A button is a component that triggers an action event when clicked.
Several types of buttons Command buttons, toggle buttons,
check boxes, radio buttons
JButton(String text)
JButton btnOne = new JButton( "Button" );
JButton(String text,Icon icon)
Icon bug1 = new ImageIcon( "bug1.gif" );
JButton btnOne = new JButton("Fancy Button",bug1 );
import java.awt.*;import javax.swing.*;
public class TestButton extends JFrame{ private JButton button; public TestButton() { super(“Button Example”); Container c = getContentPane();
c.setLayout(new FlowLayout()); button= new JButton(“Click Here”); c.add(button); setSize(200,200); setVisible(true); }
public static void main(String[] arg) { TestButton s= new TestButton(); s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
Example: Creating Button
JCheckBox()
JCheckBox(String text)
JCheckBox(String text, boolean
selected)
JCheckBox(Icon icon)
JCheckBox(String text, Icon icon)
JCheckBox(String text, Icon icon,
boolean selected)
import java.awt.*;import javax.swing.*;
public class CheckBox extends JFrame{ private JCheckBox chkBox1,chkBox2;
public CheckBox() { super(“Create CheckBox"); Container s = getContentPane(); s.setLayout(new FlowLayout()); chkBox1 = new JCheckBox("Wira"); chkBox2 = new JCheckBox("Waja",true);
s.add(chkBox1); s.add(chkBox2); setSize(400,200); setVisible(true); }
public static void main(String[] arg) { CheckBox t = new CheckBox(); t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
Radio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time.
JRadioButton()
JRadioButton(String text)
JRadioButton(String text, boolean
selected)
JRadioButton(Icon icon)
JRadioButton(String text, Icon icon)
JRadioButton(String text, Icon icon,
boolean selected)
JRadioButton rd1= new JRadioButton(“waja”);
JRadioButton rd2= new JRadioButton(“wira”);
ButtonGroup btn = new ButtonGroup();
btn.add(rd1);
btn.add(rd2);
import java.awt.*;import javax.swing.*;
public class RadioButton extends JFrame{ private JRadioButton rdButton1,rdButton2;
public RadioButton() { super("Create RadioButton"); Container s = getContentPane();
s.setLayout(new FlowLayout()); rdButton1 = new JRadioButton("wira",true); rdButton2 = new JRadioButton("Waja");
s.add(rdButton1); s.add(rdButton2);
ButtonGroup btn= new ButtonGroup(); btn.add(rdButton1); btn.add(rdButton2);
setSize(400,200); setVisible(true); }
public static void main(String[] arg) { RadioButton t = new RadioButton(); t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
If you want to let the user enter multiple lines of text, you cannot use text fields unless you create several of them.
The solution is to use JTextArea, which enables the user to enter multiple lines of text.
JTextArea(int rows, int columns)Creates a text area with the specified number of rows and columns.
JTextArea(String s, int rows, int columns)Creates a text area with the initial text andthe number of rows and columns specified.
JTextArea( s, 10, 15)
import java.awt.*;import javax.swing.*;
public class TestTextArea extends JFrame{ private JTextArea txtArea; public TestTextArea() { super(“Create TextArea"); Container c = getContentPane(); c.setLayout(new FlowLayout()); txtArea = new JTextArea(“Type here",5,20); c.add(txtArea); setSize(400,200); setVisible(true); }
public static void main(String[] arg) { TestTextArea s = new TestTextArea(); s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
A scroll pane is a component that supports automatically scrolling without coding.
Use to text area, list and etc. Constructor
JScrollPane (Component) Component – component that need to have scroll pane
Eg :JTextArea txtArea = new JTextArea(10,12);JScrollPane scroll = new JScrollPane(txtArea);
import java.awt.*;import javax.swing.*;
public class Scroll extends JFrame{ private JTextArea txtArea; private JScrollPane scroll;
public Scroll() { super("Create TextArea with Scroll Pane"); Container c = getContentPane(); c.setLayout(new FlowLayout()); txtArea = new JTextArea(“Type here",5,20); scroll = new JScrollPane(txtArea); c.add(scroll); setSize(400,200); setVisible(true); }
public static void main(String[] arg) { Scroll s = new Scroll(); s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
A text field is an input area where the usercan type in characters.
Text fields are useful in that they enable the user to enter in variable data (such as a name or a description).
JTextField(int columns)Creates an empty text field with the specified number of columns.
JTextField( 10 ) - sets textfield with 10 columns of text
JTextField(String text)Creates a text field initialized with the specified text.
JTextField( "Hi" )
JTextField(String text,int columns)Creates a text field initialized with the specified text and the column size.
getText()Returns the string from the text field.
setText(String text)Puts the given string in the text field.
setEditable(boolean editable)Enables or disables the text field to be edited. By default, editable is true.
setColumns(int)Sets the number of columns in this text field.The length of the text field is changeable.
import java.awt.*;import javax.swing.*;
public class TestTextField extends JFrame{ private JTextField txtField1,txtField2,txtField3;
public TestTextField() { super("Membuat TextField"); Container c = getContentPane();
c.setLayout(new FlowLayout());
txtField1 = new JTextField(“Enter your ID"); txtField2 = new JTextField(“Please Type",20); txtField3 = new JTextField(10);
c.add(txtField1); c.add(txtField2); c.add(txtField3); setSize(400,200); setVisible(true); }
public static void main(String[] arg) { TestTextField s = new TestTextField(); s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
A combo box is a simple list of items from which the user can choose.
It performs basically the same function as a list, but can get only one value.
To add an item to a JComboBox jcbo, use
jcbo.addItem(Object item)
To get an item from JComboBox jcbo, use
jcbo.getItem()
JComboBox jcbo = new JComboBox();
getSelectedIndex Returns the index of the currently
selected item
setMaximumRowCount( n )Eg: setMaximumRowCount( 3 );
Set the maximum number of elements to display when user clicks combo box
Scrollbar automatically provided
import java.awt.*;import javax.swing.*;
public class TestComboBox extends JFrame{ private JComboBox jcb; public TestComboBox() { super(“Create combobox"); Container c = getContentPane(); c.setLayout(new FlowLayout());
jcb = new JComboBox(); jcb.addItem("wira"); jcb.addItem("waja"); jcb.addItem(“saga”);
c.add(jcb);
setSize(400,200); setVisible(true); }
public static void main(String[] arg) { TestComboBox s = new TestComboBox(); s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
A list is a component that performs basically the same function as a combo box, but it enables the user to choose a single value or multiple values.
Does not have scrollbar, need to create it.
JList()
Creates an empty list.
JList(Object[] stringItems)
Creates a new list initialized with items.
List Properties selectionMode : determine the selection: SINGLE_SELECTION
▪ select only 1 item SINGLE_INTERVAL_SELECTION
▪ Select many items from JList and allows continuous range selection
MULTIPLE_INTERVAL_SELECTION▪ Select many items from JList and
allows discontinuous range selection
import java.awt.*;import javax.swing.*;
public class SingleList extends JFrame { private JList list; private JScrollPane scroll; String car [] = {"kancil","kelisa","wira","waja","iswara" };
public SingleList() { super(“Create single selection list"); Container c = getContentPane(); c.setLayout(new FlowLayout()); list= new JList(car) ; list.setVisibleRowCount(3); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scroll = new JScrollPane(list); c.add(scroll); setSize(400,200); setVisible(true); }
public static void main(String[] arg) { SingleList t = new SingleList(); t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
import java.awt.*;import javax.swing.*;
public class TryPanel extends JFrame { private JPanel panel1; private JLabel label; private JTextField txtField;
public TryPanel() { super("Test Panel"); Container c = getContentPane(); panel1 = new JPanel(); c.add(panel1,BorderLayout.NORTH); panel1.setLayout(new FlowLayout());
label = new JLabel("Name"); txtField = new JTextField(10); panel1.add(label); panel1.add(txtField);
setSize(300,200); setVisible(true); } public static void main(String[] arg) { TryPanel s = new TryPanel(); s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
A message dialog box simply displays a message to alert the user and waits for the user to click the OK button to close the dialog.
The messageType is one of the following constants:
JOptionPane.ERROR_MESSAGEJOptionPane.INFORMATION_MESSAGE JOptionPane.PLAIN_MESSAGEJOptionPane.WARNING_MESSAGEJOptionPane.QUESTION_MESSAGE
Example :
JOptionPane.showMessageDialog(Component parentComponent, Object msg, String title_bar, int type_of_msg);
JOptionPane.showMessageDialog(this,”User ID salah”,”contoh mesej”, JOptionPane.ERROR_MESSAGE);
Msg
title_bar
type_of_msg
import javax.swing.*;
public class TestDialog extends JFrame{ public TestDialog() {
JOptionPane.showMessageDialog(null,"Your user ID is wrong","Message", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this,"Your user ID is wrong","Message", JOptionPane.ERROR_MESSAGE);
}
public static void main(String[] arg) { TestDialog s = new TestDialog(); s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
Java provides several classes—JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem, and JRadioButtonMenuItem —to implement menus in a frame.
JMenuBar – structure or component to support menus.
A JFrame or JApplet can hold a menu bar to which the pull-down menus are attached.
Menus consist of menu items that the user can select (or toggle on or off).
Create a menu bar with frame. Example :
JFrame frame = new JFrame();frame.setSize(400,200);frame.setVisible(true);JMenuBar jmb = new JMenuBar();frame.setJMenuBar(jmb); //to add a menu bar into the frame
Method setJMenuBar() – use to add the menu bar into the frame
JMenu fileMenu = new JMenu(“File”); // create menus ‘file’JMenu helpMenu = new JMenu (“Help”); // create menus
‘help’jmb.add(fileMenu); // add menus ‘file’ into the menu barjmb.add(helpMenu); // add menus ‘help’ into the menu bar
Menu bar
JMenuItem mnuNew= new JMenuItem(“New”) // create menu item ‘New’
fileMenu.add(mnuNew); // add menu item ‘New’ into menus ‘File’JMenuItem mnuOpen= new JMenuItem(“Open”)fileMenu.add(mnuOpen);fileMenu.addSeparator();JMenuItem mnuPrint= new JMenuItem(“Print”) // create
menu item ‘Print’fileMenu.add(mnuPrint); // add menu item ‘Print’ into menus
‘File’fileMenu.addSeparator();JMenuItem mnuExit= new JMenuItem(“Exit”)fileMenu.add(mnuExit);
separator
JMenu helpMenu = new JMenu("Help"); // create menus ‘Help’JMenu mnuPerisian = new JMenu("Perisian"); // cipta menu item ‘Perisian’helpMenu.add(mnuPerisian); // add menu item ‘Perisian’ into menus ‘help’JMenuItem mnuJava = new JMenuItem("JAVA"); // cipta sub menu item
‘Java’JMenuItem mnuPascal = new JMenuItem("Pascal"); // cipta sub menu
item ‘Pascal’mnuPerisian.add(mnuJava); // add sub menu item ‘Java’ into menu item
‘Perisian’mnuPerisian.add(mnuPascal); // add sub menu item ‘Pascal’ into menu item
‘Perisian’
JMenu helpMenu = new JMenu("Help"); // create menus ‘Help’ // create menu item ‘periksa’JCheckBoxMenuItem mnuPeriksa = new
JCheckBoxMenuItem(“periksa”);
helpMenu.add(mnuPeriksa) //add menu item‘periksa’ into menus ‘Help’
JMenu helpMenu = new JMenu("Help"); // create menus ‘Help’
JMenu mnuWarna = new JMenu(“warna”); // create menu item ‘warna’
helpMenu.add(mnuWarna); // add menu item ‘warna’ into menus ‘Help’
JRadioButtonMenuItem mnuHitam = new JRadioButtonMenuItem(“hitam”);
JRadioButtonMenuItem mnuMerah = new JRadioButtonMenuItem(“merah”);
warna.add(mnuHitam); // add sub menu item ‘hitam’ intomenu item ‘warna’
warna.add(mnuMerah); // add sub menu item ‘merah’ into menu item ‘warna’
ButtonGroup bGroup = new ButtonGroup(); // button group is created
bGroup.add(mnuHitam); // radio button is grouped into bGroup
bGroup.add(mnuMerah); // radio button is grouped into bGroup
Use Alt followed by the key: example Alt+H
JMenu helpMenu = new JMenu("Help");helpMenu.setMnemonic(‘H’);JMenu mnuPerisian = new JMenu("Perisian");mnuPerisian.setMnemonic(‘P’);
Mnemonic
1. Create frame2. Create menu bar3. Add menu bar into frame 4. Create menus5. Add menus into menu bar6. Create menu item7. Add menu item into menus8. Create sub menu item 9. Add sub menu item into menu item
import java.awt.*;import javax.swing.*;
public class TestMenu extends JFrame{ public TestMenu() { setTitle(“Test Menu"); JMenuBar jmb = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem mnuNew= new JMenuItem("New"); fileMenu.add(mnuNew); JMenuItem mnuAdd= new JMenuItem("Open"); fileMenu.add(mnuAdd); fileMenu.addSeparator(); JMenuItem mnuPrint= new JMenuItem("Print"); fileMenu.add(mnuPrint); fileMenu.addSeparator(); JMenuItem mnuExit= new JMenuItem("Exit"); fileMenu.add(mnuExit);
JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('H'); JMenu mnuSoftware = new JMenu(“Software”); mnuSoftware.setMnemonic('P'); JMenuItem mnuJava = new JMenuItem("JAVA"); JMenuItem mnuPascal = new JMenuItem("Pascal"); mnuSoftware.add(mnuJava); mnuSoftware.add(mnuPascal); helpMenu.add(mnuSoftware); JCheckBoxMenuItem mnuCheck = new JCheckBoxMenuItem(“Check"); helpMenu.add(mnuCheck);
JMenu mnuColor = new JMenu(“Color"); helpMenu.add(mnuColor); JRadioButtonMenuItem mnuBlack= new JRadioButtonMenuItem(“Black”); JRadioButtonMenuItem mnuRed = new JRadioButtonMenuItem(“Red"); mnuColor.add(mnuBlack); mnuColor.add(mnuRed); ButtonGroup bGroup = new ButtonGroup();
bGroup.add(mnuBlack); bGroup.add(mnuRed);
jmb.add(fileMenu); jmb.add(helpMenu);
setJMenuBar(jmb); setSize(400,200); setVisible(true); }
public static void main(String[] arg) {
TestMenu s = new TestMenu();s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
In this class, you learnt the following:
Swing is a set of program components for Java programmers that provide the ability to create graphical user interface ( GUI ) components, such as buttons and scroll bars, that are independent of the windowing system for specific operating system .