0% found this document useful (0 votes)
28 views25 pages

CH 1 AWT and SWING

The document provides information about AWT and Swing components in Java. It discusses the differences between AWT and Swing, with Swing being designed to solve AWT's portability and layout issues. The document then describes several common Swing components: JButton, JCheckBox, JRadioButton, JLabel, JTextField, JTextArea, and JComboBox. For each component, it provides the class hierarchy and constructor details.

Uploaded by

Legesse Samuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views25 pages

CH 1 AWT and SWING

The document provides information about AWT and Swing components in Java. It discusses the differences between AWT and Swing, with Swing being designed to solve AWT's portability and layout issues. The document then describes several common Swing components: JButton, JCheckBox, JRadioButton, JLabel, JTextField, JTextArea, and JComboBox. For each component, it provides the class hierarchy and constructor details.

Uploaded by

Legesse Samuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Advanced Programming

(CoSc2084)
Chapter 1: AWT and Swing
Swing vs AWT
• AWT (Abstract Window Toolkit) is Java’s original set of
classes for building GUIs
– Uses peer components of the OS; heavyweight
– Not truly portable: looks different and lays out inconsistently on
different OSs
• Due to OS’s underlying display management system
• Swing is designed to solve AWT’s problems
– 99% java; lightweight components
• Drawing of components is done in java
• Uses 4 of AWTs components
– Window, frame, dialog, ?
– Lays out consistently on all OSs
– Uses AWT event handling
• For AWT: import java.awt.*;
• For Swing:import javax.swing.*;
• Swing is bigger and slower
• Swing is more flexible and better looking
• Swing and AWT are incompatible--you can use
either, but you can’t mix them
• Learning the AWT is a good start on learning Swing
• AWT: Button b = new Button (“OK”);
• Swing: Jbutton b = new Jbutton(“OK”);
Components Covered in the Chapter
•Introduces the frequently used GUI components
•Uses borders and icons
JButton
Component Container JComponent AbstractButton JCheckBox
JToggleButton
JLabel JRadioButton
JTextArea

JTextComponent
JTextField JPasswordField
JComboBox

JList

JScrollBar

JSlider
JButton
JButton inherits AbstractButton and provides
several constructors to create buttons.

javax.swing.AbstractButton

javax.swing.JButton
+JButton() Creates a default button with no text and icon.
+JButton(icon: javax.swing.Icon) Creates a button with an icon.
+JButton(text: String) Creates a button with text.
+JButton(text: String, icon: Icon) Creates a button with text and an icon.
JCheckBox
• JCheckBox inherits all the properties such as text, icon,
mnemonic, verticalAlignment, horizontalAlignment,
horizontalTextPosition, verticalTextPosition, and selected from
AbstractButton, and provides several constructors to create
check boxes.
javax.swing.AbstractButton

javax.swing.JToggleButton

javax.swing.JCheckBox
+JCheckBox() Creates a default check box button with no text and icon.
+JCheckBox(text: String) Creates a check box with text.
+JCheckBox(text: String, selected: Creates a check box with text and specifies whether the check box is
boolean) initially selected.
+JCheckBox(icon: Icon) Creates a checkbox with an icon.
+JCheckBox(text: String, icon: Icon) Creates a checkbox with text and an icon.
+JCheckBox(text: String, icon: Icon, Creates a check box with text and an icon, and specifies whether the check
selected: boolean) box is initially selected.
JRadioButton
• Radio buttons are variations of check boxes.
They are often used in the group, where only
one button is checked at a time.
javax.swing.AbstractButton

javax.swing.JToggleButton

javax.swing.JRadioButton
+JRadioButton() Creates a default radio button with no text and icon.
+JRadioButton(text: String) Creates a radio button with text.
+JRadioButton(text: String, selected: Creates a radio button with text and specifies whether the radio button is
boolean) initially selected.
+JRadioButton(icon: Icon) Creates a radio button with an icon.
+JRadioButton(text: String, icon: Icon) Creates a radio button with text and an icon.
+JRadioButton(text: String, icon: Icon, Creates a radio button with text and an icon, and specifies whether the radio
selected: boolean) button is initially selected.
Grouping Radio Buttons
ButtonGroup btg = new ButtonGroup();
btg.add(jrb1);
btg.add(jrb2);
JLabel
A label is a display area for a short text, an
image, or both.
javax.swing.JComponent
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JLabel
-text: String The label’s text.
-icon: javax.swing.Icon The label’s image icon.
-horizontalAlignment: int The horizontal alignment of the text and icon on the label.
-horizontalTextPosition: int The horizontal text position relative to the icon on the label.
-verticalAlignment: int The vertical alignment of the text and icon on the label.
-verticalTextPosition: int The vertical text position relative to the icon on the label.
-iconTextGap: int The gap between the text and the icon on the label (JDK 1.4).
+JLabel() Creates a default label with no text and icon.
+JLabel(icon: javax.swing.Icon) Creates a label with an icon.
+JLabel(icon: Icon, hAlignment: int) Creates a label with an icon and the specified horizontal alignment.
+JLabel(text: String) Creates a label with text.
+JLabel(text: String, icon: Icon, Creates a label with text, an icon, and the specified horizontal alignment.
hAlignment: int)
+JLabel(text: String, hAlignment: int) Creates a label with text and the specified horizontal alignment.
JTextField
• A text field is an input area where the user can 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).
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.text.JTextComponent
-text: String The text contained in this text component.
-editable: boolean Indicates whether this text component is editable (default: true).

javax.swing.JTextField
-columns: int The number of columns in this text field.
-horizontalAlignment: int The horizontal alignment of this text field (default: LEFT).
+JTextField() Creates a default empty text field with number of columns set to 0.
+JTextField(column: int) Creates an empty text field with specified number of columns.
+JTextField(text: String) Creates a text field initialized with the specified text.
+JTextField(text: String, columns: int) Creates a text field initialized with the specified text and columns.
JTextField Methods
• 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.
JTextArea
• 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.
javax.swing.text.JTextComponent The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JTextArea
-columns: int The number of columns in this text area.
-rows: int The number of rows in this text area.
-tabSize: int The number of characters used to expand tabs (default: 8).
-lineWrap: boolean Indicates whether the line in the text area is automatically wrapped (default:
false).
-wrapStyleWord: boolean Indicates whether the line is wrapped on words or characters (default: false).
+JTextArea() Creates a default empty text area.
+JTextArea(rows: int, columns: int) Creates an empty text area with the specified number of rows and columns.
+JTextArea(text: String) Creates a new text area with the specified text displayed.
+JTextArea(text: String, rows: int, columns: int) Creates a new text area with the specified text and number of rows and columns.
+append(s: String): void Appends the string to text in the text area.
+insert(s: String, pos: int): void Inserts string s in the specified position in the text area.
+replaceRange(s: String, start: int, end: int): Replaces partial text in the range from position start to end with string s.
void
+getLineCount(): int Returns the actual number of lines contained in the text area.
JComboBox
• 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.
javax.swing.JComponent

javax.swing.JComboBox
+JComboBox() Creates a default empty combo box.
+JComboBox(items: Object[]) Creates a combo box that contains the elements in the specified array.
+addItem(item: Object): void Adds an item to the combo box.
+getItemAt(index: int): Object Returns the item at the specified index.
+getItemCount(): int Returns the number of items in the combo box.
+getSelectedIndex(): int Returns the index of the selected item.
+setSelectedIndex(index: int): void Sets the selected index in the combo box.
+getSelectedItem(): Object Returns the selected item.
+setSelectedItem(item: Object): void Sets the selected item in the combo box.
+removeItem(anObject: Object): void Removes an item from the item list.
+removeItemAt(anIndex: int): void Removes the item at the specified index in the combo box.
+removeAllItems(): void Removes all items in the combo box.
JComboBox Methods
To add an item to a JComboBox jcbo, use
jcbo.addItem(Object item)

To get an item from JComboBox jcbo, use


jcbo.getItem()
JList
• 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.
javax.swing.JComponent

javax.swing.JList
+JList() Creates a default empty list.
+JList(items: Object[]) Creates a list that contains the elements in the specified array.
+getSelectedIndex(): int Returns the index of the first selected item.
+setSelectedIndex(index: int): void Selects the cell at the specified index.
+getSelectedIndices(): int[] Returns an array of all of the selected indices in increasing order.
+setSelectedIndices(indices: int[]): void Selects the cells at the specified indices.
+getSelectedValue(): Object Returns the first selected item in the list.
+getSelectedValues(): Object[] Returns an array of the values for the selected cells in increasing index order.
+getVisibleRowCount(): int Returns the number of visible rows displayed without a scrollbar. (default: 8)
+setVisibleRowCount(count: int): void Sets the preferred number of visible rows displayed without a scrollbar.
+getSelectionBackground(): Color Returns the background color of the selected cells.
+setSelectionBackground(c: Color): void Sets the background color of the selected cells.
+getSelectionForeground(): Color Returns the foreground color of the selected cells.
+setSelectionForeground(c: Color): void Sets the foreground color of the selected cells.
+getSelectionMode(): int Returns the selection mode for the list.
Read about
• JScrollBar
• Jslider
• JMenuBar
• Jmenu
• JMenuItem
• Jtable and more java components
Component and Container
• Component contributes several public methods to all its
subclasses:
public void setSize(int width, int height);
//set size in pixels
public void setBackground(Color c);
//see class Color for colors
public void setVisible(boolean b);
//Display on screen (creates peer)

• Container is an abstract class:


– It cannot be instantiated; subclasses must implement some methods
– Container does implement some useful methods, including:
public Component add(Component comp);
//put a Component in a Container
public setLayout(LayoutManager mgr);
//lay out components in some pattern
Containers
A container is a component that
 Can hold other components  There are three basic top-
 Has a layout manager level containers
Heavyweight vs. lightweight  JWindow: top-level window
 A heavyweight component with no border
interacts directly with the host  JFrame: top-level window with
system border and (optional) menu bar
 JWindow, JFrame, and JDialog are  JDialog: used for dialog
heavyweight windows
 Except for these top-level
containers, Swing components are  Another important container
almost all lightweight
JPanel is lightweight
 JPanel: used mostly to
organize objects within other
containers
Window and Frame classes
• A Window is a top-level window with no borders and no menubar
– It can generate a WindowOpened or a WindowClosed event,
to which a WindowListener or WindowAdapter can respond

• A Frame is a top-level window with a title and a border


• Because it has more features, it can generate more events:
WindowOpened, WindowClosing,
WindowClosed,
WindowIconified, WindowDeiconified,
WindowActivated, WindowDeactivated

• Respond to these events with a WindowListener


• Once a subclass of Container has been constructed, it can add
(attach) any AWT component within it, such as a Button, Label,
TextField, or another Frame or Panel
Layout Managers
• A layout manager controls placement and sizing of components in a container
– If you do not specify a layout manager, the container will use a default:
• JPanel default = FlowLayout
• JFrame default = BorderLayout

 General syntax
• container.setLayout(new LayoutMan());

 Examples:

• JPanel p1 = new JPanel(new BorderLayout());


• JPanel p2 = new JPanel();
• p2.setLayout(new BorderLayout());

• Five common layout managers:


BorderLayout, BoxLayout, FlowLayout, GridBagLayout, GridLayout
• FlowLayout
– Components placed from left to right in order added
– When a row is filled, a new row is started
– Lines can be centered, left-justified or right-justified (see FlowLayout constructor)
– See also BoxLayout

• GridLayout
– Components are placed in grid pattern
– number of rows & columns specified in constructor
– Grid is filled left-to-right, then top-to-bottom
 BorderLayout
 Divides window into five areas: North, South, East, West, Center

 Adding components
 FlowLayout and GridLayout use container.add(component)
 BorderLayout uses container.add(component, index) where
index is one of
 BorderLayout.NORTH
 BorderLayout.SOUTH
 BorderLayout.EAST
 BorderLayout.WEST
 BorderLayout.CENTER

Note: read more about Layout Managers


Events and Event Handling
• Components (AWT and Swing) generate events in response to
user actions
– (button clicks, mouse movement, item selection…)
– different components generate different events
• Buttons generate “action” events
• Cursor movement generates “mouse events” ect.
– The program must provide event handlers to catch and process events
• Unprocessed events are passed up through the event hierarchy
and handled by a default (do nothing) handler
When you design GUI
• Determine which components you want
• Choose a top-level container in which to put
the components (JFrame is often a good
choice)
• Choose a layout manager to determine how
components are arranged
• Place the components
• Next class you came with Project title and list
of group members.

You might also like