0% found this document useful (0 votes)
3 views

Chapter 3

Chapter Three discusses Java GUI, comparing console applications with graphical user interfaces (GUIs) that utilize components like buttons and text fields for user interaction. It covers the use of JOptionPane for simple input and output, the differences between AWT and Swing, and introduces various GUI components and their functionalities. The chapter also outlines the steps to build a GUI and provides details on creating frames and buttons in Java applications.

Uploaded by

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

Chapter 3

Chapter Three discusses Java GUI, comparing console applications with graphical user interfaces (GUIs) that utilize components like buttons and text fields for user interaction. It covers the use of JOptionPane for simple input and output, the differences between AWT and Swing, and introduces various GUI components and their functionalities. The chapter also outlines the steps to build a GUI and provides details on creating frames and buttons in Java applications.

Uploaded by

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

Chapter Three

Java GUI

6/7/2023 1
Introduction
 Computer programs can use a console or a GUI to interact with the user

 Console applications use text-based program output and keyboard entered user input.

 GUIs use a graphical window or windows that provide interaction with the user.

 GUI’s accept input from both the keyboard and a mouse, and a variety of other input devices.

 A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an
application.

 It gives an application a distinctive ―look‖ and ―feel.‖

 GUIs are built from GUI components. These are sometimes called controls or widgets. (short
for window gadgets—in other languages)
2
Simple GUI-Based I/O with JOptionPane
 The following simple addition application uses two input dialogs to obtain integers from
the user and a message dialog to display the sum of the integers the user enters.
import javax.swing.JOptionPane;
public class Addition {
public static void main( String args[] ) {
String firstNum = JOptionPane.showInputDialog("Enter first integer―);
int number1 = Integer.parseInt(firstNum);
String secondNum = JOptionPane.showInputDialog("Enter second integer" );
int number2 = Integer.parseInt( secondNum );
int sum = number1 + number2; // add numbers
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );
}}
3
Cont …
 Java’s JOptionPane class (package javax.swing) provides prepackaged dialog boxes for both
input and output.

 These dialogs are displayed by invoking static JOptionPane methods.


showInputDialog method displays an input dialog using the method’s String argument
("Enter first integer") as a prompt . It has a text box and two buttons ok and Cancel
showMessageDialog method is used to display a message dialog containing the sum.
 The first argument helps the Java application determine where to position the dialog
box.
 The value null indicates that the dialog should appear in the center.
 It can also be used to specify that the dialog should appear centered over a particular
window of the computer screen.
4
Cont …
 The second argument is the message to display, in this case, the result of concatenating
the String "The sum is " and the value of sum.
 The third argument—"Sum of Two Integers"—represents the string that should appear
in the dialog’s title bar at the top of the dialog.
 The fourth argument:- JOptionPane.PLAIN_MESSAGE—is the type of message
dialog to display. A PLAIN_MESSAGE dialog does not display an icon to the left of
the message. Other possible constants are: ERROR_MESSAGE,
INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE.

• Class JOptionPane provides several overloaded versions of methods showInputDialog and


showMessageDialog, as well as methods that display other dialog types.
5
AWT vs Swing
• Java has two GUI packages, the original Abstract Windows Toolkit (AWT)
and the newer Swing.
• When java was introduced, the GUI classes were bundled in a library
known as Abstract Windows Toolkit(AWT).
• AWT (Abstract Window Toolkit) is Java’s original set of classes for
building GUIs.
Uses peer components of the OS; heavyweight.
Uses the native operating system's window routines so the visual effect
is dependent on the run-time system platform.

6
Cont …
For every platform on which Java runs, the AWT components are automatically mapped

to the platform-specific components through their respective agents, known as peers.

Not truly portable: looks different and lays out inconsistently on different OSs. The

application's GUI components display differently on each platform.

Is adequate for many applications but it is difficult to build an attractive GUI.

7
Cont …

Swing: is designed to solve AWT’s problems (since Java 2 ).

99% java; lightweight components: drawing of components is done in java.

Swing GUI components allow you to specify a uniform look-and-feel for your
application across all platforms.

Lays out consistently on all Oss.

Much bigger set of built-in components.

Uses AWT event handling.

8
AWT vs Swing…

• Swing is built ―on top of‖ AWT, so you need to import AWT and use a few
things from it.

• 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.

9
AWT vs Swing…

• Basic components/controls are practically the same in both


AWT: Button b = new Button ("OK");
Swing: JButton b = new JButton("OK");

• Swing gives far more options for everything (buttons with pictures on them, etc.)

• AWT classes are contained inside package java.awt while

• Swing classes are located in package javax.swing.


10
GUI Classes
• The GUI classes can be classified into three groups:
 Container class,
 Helper class, and
 Component classes.

Container classes
• A GUI is built by putting components/controls into containers.
• Container is used to group components.
• Frames, Panels and applets are examples of containers.
• Important container classes are JFrame, JApplet, and JPanel.

11
1. GUI Container Classes
JFrame
A resizable, movable window with title bar and close button.
Usually it contains JPanels.
It is a containers that holds other Swing user-interface components in Java GUI
application.
JPanel
A region internal to a JFrame or another JPanel.
Used for grouping components together.
Optionally bounded by a visible border.
Lives inside some enclosing Container.
Panels can be nested:
You can place panels inside a container that includes a panel.

12
Cont …
The terms ―pane‖ and ―panel‖ are used interchangeably in Java.

If a frame is a window, a pane is the glass.

Panes hold a window’s GUI components.

Every frame has at least one pane, the default ―Content Pane‖.

JApplet

Is a subclass of Applet .

Represents the featureless Window provided by the browser for an Applet to


run in.

13
2. GUI Component Classes…
GUI Components or Controls (also known as "widgets")

• Are the basic user interface elements the user interacts with: labels, buttons, text
fields, ...

• The visual arrangement of the components depends on the container's layout.

• When the user does something to a component, the component's listener is sent an
event.

14
Swing GUI Components
JCheckBoxMenuItem

JMenuItem JMenu

AbstractButton JButton JRadioButtonMenuItem

JToggleButton JCheckBox

JRadioButton
JComponent JEditorPane

JTextComponent JTextField JPasswordField

JTextArea

JLabel JList JComboBox JPanel JOptionPane JScrollBar JSlider

JTabbedPane JSplitPane JLayeredPane JSeparator JScrollPane JRootPane

JToolBar JMenuBar JPopupMenu JFileChooser JColorChooser JToolTip

JTree JTable JTableHeader JInternalFrame JProgressBar JSpinner


15
15
Swing GUI Components
• Input Components
• Buttons ( JButton, JRadioButtons, JCheckBox)
• Text (JTextField, JTextArea)
• Menus (JMenuBar, JMenu, JMenuItem)
• Sliders (JSlider)
• JComboBox (uneditable) (JComboBox)
• List (Jlist )
• Information Display Components
• JLabel
• Progress bars (JProgressBar)
• Tool tips (using JComponent's setToolTipText(s) method)
• Choosers
• File chooser (JFileChooser)
• Color chooser (JColorChooser)

16
Swing GUI Components …
 More complex displays
• Tables (JTable)
• Trees (JTree)
• Formatted Text

 Every GUI components has

• Properties
JButton
• Methods

• Events

17
3. GUI Helper Classes
GUI Helper Classes
 They are used to describe the properties of GUI components such as graphics context,
colors, fonts, and dimension.
Graphics
 Is an abstract class that provides a graphical context for drawings strings, lines, and
simple shapes.
Color:
 Deals with the colors of GUI components.
For example:- you can specify background colors in components like Jframe and
Jpanel. You can specify colors of lines, shapes,…..

18
GUI Class…
Font
 Specify fonts for the text and drawings on GUI components.
Example:- You can specify the font type(e.g. SansSerif), style (e.g. bold), and size(e.g.
24 points) for the text on the button.
Font f=new Font();
LayoutManager
 Is an interface whose instances specify how components are arranged in a
container.
The helper classes are in the java.awt package.
• The Swing components do not replace all the classes in AWT, only AWT GUI
components classes (e.g. Button, TextField, TextArea).
• The AWT helper classes remain unchanged.

19
GUI Helper Classes

Dimension Classes in the java.awt


LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

JComponent JPanel Swing Components


in the javax.swing package

Lightweight
20
20
Steps to build a GUI

1. Make a Container:– you need to create either a frame or an applet to hold the user-
interface components.

2. Create some more Components (buttons, text areas, etc.).

3. Add your Components to your display area:- Choose a layout manager.

4. Attach Listeners to your Components:- interacting with a component causes an Event


to occur.

21
Creating a Frames
Frame
• Is an independent window that has decorations such as a border, a title and buttons for
closing, minimizing and maximizing the window.
• Frame is a window that is not contained inside another window.
• Can be moved around on the screen independently of any other GUI windows.

• Applications with a GUI typically use at least one frame.

• Frame is the basis to contain other user interface components in Java GUI applications.

22
Creating a Frames

• The JFrame class can be used to create windows.

JFrame frame = new Jframe();

JFrame class Constructor summary

JFrame()
Constructs a new frame with no title and it is initially invisible.
JFrame(String title)
Creates a new, initially invisible Frame with the specified
title. 23
JFrames…
JFrame Class Methods
javax.swing.JFrame
+setSize(width: int, height: int): void Specifies the size of the frame.
+setLocation(x: int, y: int): void Specifies the upper-left corner location of the frame.
+setVisible(visible: boolean): void Sets true to display the frame.
+setDefaultCloseOperation(mode: int): void Specifies the operation when the frame is closed.
+setLocationRelativeTo (c: Component): void Sets the location of the frame relative to the specified
component. If the component is null,
the frame is centered on the screen.

setBounds(int x, int y, int width,Int height)


 Specifies the size of the frame and the location of the upper left corner.
 This puts the upper left corner at location (x, y), where x the number of pixels from the
left of the screen and y is the number from the top of the screen. height and width are as
before.
24
JFrame Class Methods
 public void setDefaultCloseOperation(int mode): is used to specify one of several options for the
close button.
Use one of the following constants to specify your choice:
oJFrame.EXIT_ON_CLOSE:- Exit the application.
oJFrame.HIDE_ON_CLOSE:- Hide the frame, but keep the application running.
oJFrame.DO_NOTHING_ON_CLOSE:- Ignore the click.
import javax.swing.*;
public class JFrameSample {
public static void main(String[] args) {
JFrame frame = new JFrame(“First JFrame");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}
25
Jframe …
• The frame is not display until the frame.setVisibile(true) method is
invoked.

• frame.setSize(400, 300)specifies that the frame is 400 pixels wide


and 300 pixels high.

• If the setSize and setVisible methods are both defined in the


Component class, they are inherited by the JFrame class.

• Invoking setLocationRelativeTo(null) centers the frame on the


screen.

26
JFrame…
 Invoking setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) tells the program to
terminate when the frame is closed.

If you forget to call setDefaultCloseOperation() you will get JFrame.HIDE_ON_CLOSE


by default.

• Thus the program does not terminate when the frame is closed.

• In that case, you have to stop the program by pressing Ctrl + C.

• The setTitle(String text) method is defined in the java.awt.Frame class.

• Since JFrame is subclass of Frame, you can use it to set a title for an object of JFrame.

27
GUI Components
• Introduces the frequently used GUI components

JButton
Component Container JComponent AbstractButton JCheckBox
JToggleButton
JRadioButton
JLabel
JTextArea

JTextComponent
JTextField JPasswordField
JComboBox

JList

JScrollBar

JSlider

28
28
JButton
• A button is a component that triggers an action event when clicked.

• Swing provides regular buttons, toggle buttons, check box buttons, and radio buttons.

• The common features of these buttons are generalized in javax.swing.AbstractButton.

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

29
29
JButton
JButton Constructors.

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.

30
30
JButton
JButton Properties/Data Fields

 text
 icon
 mnemonic
 horizontalAlignment
 verticalAlignment
 horizontalTextPosition
 verticalTextPosition
 iconTextGap
31
31
Some Useful JButton Methods
public void setText(String text)
• Sets the button's text. JButton button= new JButton();
public String getText() button.setText(“Click Here”); OR
• Returns the button's text. JButton button= new JButton(“Click Here");
public void setEnabled(boolean b)
• Enables (or disables) the button.
public void setSelectedIcon(Icon selectedIcon)
• Sets the selected icon for the button.
public boolean isSelected()
• Returns the state of the button. True if the
toggle button is selected, false if it's not.

32
JLabel
A label is a display area for a short text(a non-editable), 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:
33 String, hAlignment: int) Creates a label with text and the specified horizontal alignment.
33
JLabel
The constructors for labels are as follows
JLabel()
• Creates a default label with no text and icon.
JLabel(String text)
• Creates a label with text.
JLabel(Icon icon)
• Creates a label with an icon.
JLabel(String text, int horizontalAlignment)
• Creates a label with a text and the specified horizontal
alignment.
JLabel(Icon icon, int horizontalAlignment)
• Creates a label with an icon and the specified horizontal
alignment.
JLabel(String text, Icon icon, int horizontalAlignment)
• Creates a label with text, an icon, and the specified horizontal
alignment.
34
34
JLabel
JLabel Properties
• JLabel inherits all the properties from JComponent and has many properties similar to the ones in JButton,
such as text, icon, horizontalAlignment,verticalAlignment, horizontalTextPosition, verticalTextPosition,
and iconTextGap.

Some Useful JLabel Methods


public String getText()
• Returns a string containing the text in the label component
public void setText(String)
• Sets the label component to contain the string value
public Icon getIcon()
• Returns the graphic image (icon) that the label displays.
public void setIcon(Icon icon)
• Defines the icon this component will display. If the value of icon is null, nothing is displayed.
35
35
JLabel
Using Labels
// Create an image icon from image file
ImageIcon icon = new ImageIcon("image/grapes.gif");

// Create a label with text, an icon, with centered horizontal alignment


JLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER);

// Set label's text alignment and gap between text and icon
jlbl.setHorizontalTextPosition(SwingConstants.CENTER);
jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);
jlbl.setIconTextGap(5);

36
36
JTextField
• A text field is a box that contains a line of text. The user can type text
into the box and the program can get it and then use it as data.
•Text fields are useful in that they enable the user to enter in variable data.
•JTextField is swing class for an editable text display.

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.
37columns: int)
+JTextField(text: String, Creates a text field initialized with the specified text and columns.
37
JTextField
JTextField Constructors: JTextField Properties
• JTextField() • text
Creates a default empty text field with number of columns set to 0. • horizontalAlignment
• JTextField(int columns)
• editable
Creates an empty text field with the specified number of columns.
• columns
• JTextField(String text)
Creates a text field initialized with the specified text.
• JTextField(String text, int columns)
Creates a text field initialized with the specified text and the column size.

38
JTextField
• public String getText()
Returns the string from the text field.
• public void setText(String text)
Puts the given string in the text field.
• public void setEditable(boolean editable)
Enables or disables the text field to be edited. By default, editable is true.
• public void setColumns(int)
Sets the number of columns in this text field.The length of the text field is changeable.

public void select(int selectionStart, int selectionEnd)


Selects the text between the specified start and end positions.
public String getSelectedText()
Returns the text value that has been highlighted in the text field.
public void append(String value)
Appends the text value of the string to the already existing text in the component.
39
39
JTextField
Using Text Fields
JLabel Fname= new JLabel("First Name");
JTextField text = new JTextField(10);

JLabel Lname= new JLabel("Last Name");


JTextField text1 = new JTextField("Text1",10);

text.setEditable(false);
add(Fname); add(text); add(Lname); add(text1);

40
40
JPasswordField….
• Allows the editing of a single line of text where the view indicates something was typed, but does
not show the original characters.

• JPasswordField class is subclass of JTextField class.

JPasswordField Constructor Summary


• JPasswordField(): Constructs a new JPasswordField, with a default document, null starting text
string, and 0 column width.
• JPasswordField(int columns): Constructs a new empty JPasswordField with the specified number
of columns.
• JPasswordField(String text): Constructs a new JPasswordField initialized with the specified text.
• JPasswordField(String text, int columns): Constructs a new JPasswordField initialized with the
specified text and columns.
41
JPasswordField….

JLabel lb = new JLabel(“Password”);


JPasswordField password = new JPasswordField(10);

42
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 class, 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.
43 43
JTextArea….
JTextArea Constructors JTextArea Properties:

• text
JTextArea(int rows, int columns)
• editable
Creates a text area with the specified number of
• columns
rows and columns.
• lineWrap
JTextArea(String s, int rows, int columns) • wrapStyleWord
Creates a text area with the initial text and • rows
the number of rows and columns specified. • lineCount
• tabSize

44
44
JTextArea
Text Area

Effect of Scroll Pane

JTextArea textArea = new JTextArea(20, 20);


JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setEditable(true);
JPanel p = new JPanel();
p.add(scrollPane);

45
JTextArea…

46
JCheckBox

 JCheckBox is a widget that has two states. On and Off. It is a box with a label.

 If the checkbox is checked, it is represented by a tick in a box.

 JCheckBox inherits all the properties from AbstractButton such as:

text, icon, mnemonic, verticalAlignment, horizontalAlignment,


horizontalTextPosition, verticalTextPosition, and selected.

 Provides several constructors to create check boxes.

47
47
JCheckBox …

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.

48
48
JCheckBox …
JCheckBox Constructor Summary
• JCheckBox()
Creates an initially unselected check box button with no text, no icon.
• JCheckBox(Icon icon)
Creates an initially unselected check box with an icon.
• JCheckBox(Icon icon, boolean selected)
Creates a check box with an icon and specifies whether or not it is initially selected.
• JCheckBox(String text)
Creates an initially unselected check box with text.

• JCheckBox(String text, boolean selected)


Creates a check box with text and specifies whether or not it is initially selected.
• JCheckBox(String text, Icon icon)
Creates an initially unselected check box with the specified text and icon.
• JCheckBox(String text, Icon icon, boolean selected)
Creates a check box with text and icon, and specifies whether or not it is initially selected.

49
JCheckBox…

JCheckBox red = new JCheckBox(―Red‖, true);


JCheckBox blue = new JCheckBox(―Blue‖);
JCheckBox green = new JCheckBox(―Green‖);
JCheckBox yellow = new JCheckBox(―Yellow‖);

50
JRadioButton

• Radio buttons are variations of check boxes.


• They are often used in the group, where only one button is checked at a time.

51
51
JRadioButton

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.

52
52
JRadioButton

JRadioButton bird = new JRadioButton("Bird");


JRadioButton cat = new JRadioButton("Cat");
JRadioButton dog = new JRadioButton("Dog");
add(bird);
add(cat);
add(dog);

53
JRadioButton…

JRadioButton bird = new JRadioButton("Bird");


JRadioButton cat = new JRadioButton("Cat");
JRadioButton dog = new JRadioButton("Dog");
add(bird); add(cat); add(dog);
ButtonGroup bg = new ButtonGroup();
bg.add(bird); bg.add(cat); bg.add(dog);
54
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.
+setSelectionMode(selectionMode: int): Sets the selection mode for the list.
55 55
Jlist …
JList Constructors
• JList(): Creates an empty list.

• JList(Object[] stringItems);Creates a new list initialized with items.

Jlist Methods
void setSelectionMode(int selectionMode)
 Determines whether single-item or multiple-item selections are allowed.
selectionMode:- is one of the three values (SINGLE_SELECTION,
SINGLE_INTERVAL_SELECTION, MULTIPLE_INTERVAL_SELECTION).
int getSelectionMode()
 Returns whether single-item or multiple-item selections are allowed.
Object[] getSelectedValues()
• Returns an array of the values for the selected cells.

56
56
JList Methods…
Object getSelectedValue()
• Returns the first selected value, or null if the selection is empty.
void setListData(Object[ ] listData)
• Constructs a ListModel from an array of objects and then applies setModel to it.

Color getSelectionBackground()
 Returns the background color for selected cells.
Color getSelectionForeground()
 Returns the selection foreground color.
void setSelectionBackground(Color selectionBackground)
 Sets the background color for selected cells.
void setSelectionForeground(Color selectionForeground)
 Sets the foreground color for selected cells.
int getSelectedIndex()
 Returns the first selected index; returns -1 if there is no selected item.
57
57
JList…

JList Properties
• selectedIndexd
• selectedIndices
• selectedValue
• selectedValues
• selectionMode
• visibleRowCount

58
58
Jlist…

String[] str={“Math”,”Computer”,”Physics”,”Chemistry”};
JList list = new JList(str);
JPanel p = new JPanel();
p.add(list);

59
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.
60
60
JComboBox….
JComboBox Methods
void addItem(Object AnObject)
• Adds an item to the item list.
Object getItemAt(int index)
• Returns the list item at the specified index.
int getItemCount()
• Returns the number of items in the list.
int getSelectedIndex()
• Returns the first item in the list that matches the given item.

61
61
JComboBox….
JComboBox Methods
Object getSelectedItem()
 Returns the current selected item.
void removeAllItems()
 Removes all items from the item list.
void removeItem(Object anObject)
 Removes an item from the item list.
void removeItemAt(int anIndex)
 Removes the item at anIndex This method works only if the
JComboBox uses a mutable data model.
void setEnabled(boolean b)
 Enables the combo box so that items can be selected.

62
62
JComboBox….

String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };


//Create the combo box, select item at index 4.
//Indices start at 0, so 4 specifies the pig.
JComboBox petList = new JComboBox(petStrings);
petList.setSelectedIndex(4);

63
63
Menu Components

64
Menu Components…
import java.awt.*;import javax.swing.*;
public class MainClass {
public static void main(String args[]) {
JFrame f = new JFrame("JMenuBar Sample");
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Sample Menu");
/JMenuItem menuItem1=new JMenuItem(“Sub Menu 1”);
menu.add(menuItem1);
JMenuItem menuIte2 = new JMenuItem(“Sub Menu 2”);
menu.add(menuItem2);
JMenuItem menuItem3 = new JMenuItem(“Sub Menu 3”);
menu.add(menuItem3);
bar.add(menu);
f.setJMenuBar(bar);

}
}

65
Adding Components into a Frame
• Each JFrame contains a content pane.

• A content pane is an instance of java.awt.Container.

• The GUI components such as buttons are placed in the content pane in a
frame.

• Prior to JDK 1.5, you have to use the getContentPane() method in the
JFrame class to return the content pane of the frame, and then invoke the
content pane’s add method to place a component into a content pane.

66
Adding Components into a Frame
• This was cumbersome, JDK 1.5 allows you to place the components to the content pane
by invoking a frame’s add method.

• This new feature is called content pane delegation.

• Strictly speaking, a component is added into the content pane of the frame.

• But for simplicity we say that a component is added to a frame.

• When a component is added to a container, a reference to the component is added to the


list of components in the container.

67
Adding Components into a Frame

// Add a button into the frame


Jbutton jbt = new Jbutton(―OK‖);
frame.getContentPane().add(jbt);

OR

frame.getContentPane().add(new JButton("OK"));

Title bar

Content pane

68
68
Adding Components into a Frame

Content Pane Delegation in JDK 1.5


Title bar // Add a button into the frame
Jbutton jbt = new Jbutton(“OK”);
frame.getContentPane().add(jbt);
OR
frame.getContentPane().add(new JButton("OK"));

Content pane

// Add a button into the frame


JButton jbt = new Jbutton(“OK”)
frame.add(jbt);
OR
69 frame.add(new JButton("OK"));
69
Adding Components into a Frame
import javax.swing.*;
public class MyFrameWithComponents {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrameWithComponents");

// Add a button into the frame


JButton jbtOK = new JButton("OK");
frame.add(jbtOK);

frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // New since JDK 1.4
}
}
70
Adding Components into a Frame

• The add(component c) method defined in the container class adds an


instance of component.

• To remove a component from a container, use the


remove(component c) method.

• The following statements removes the button from the container.


Example: frame.remove(jbtOK);

71
Adding Components into a Frame

 When you run the above program MyFrameWithComponents, the


button is always centered in the frame and occupies the entire frame
no matter how you resize it.

 This is because components are put in the frame by the content


pane’s layout manager, and the default layout manager for the
content pane places the button in the center.

 Set layout Manager before adding components.

 In the next section, you will use several different layout managers to
place components in other location as desired.

72
Layout Management

• Layouts tell Java where to put components in containers (JPanel, content pane, etc).

• Layout manager is created using LayoutManager class.

• Every layout manager class implements the LayoutManager class.

• Each layout manager has a different style of positioning components.

• If you don't specify otherwise, the container will use a default layout manager.

• Every panel (and other container) has a default layout, but it's better to set the layout
explicitly for clarity.

73
Layout Management

• Layout managers are set in containers using the


setLayout(LayoutManager) method.

Example:
LayoutManager layoutManager = new XLayout();
container.setLayout(layoutManager);

• Java supplies several layout managers: these are

74
Layout Management…
BorderLayout GridLayout
FlowLayout

Left to right, w e
c
Top to bottom

CardLayout GridBagLayout null

none,
One at a time JButton programmer
sets x,y,w,h

75
FlowLayout
• Simplest layout manager.
• Components are placed left to right in the order in which they
were added.
• When one row is filled, a new row is started.
• Components can be right aligned, centered or left aligned by
using FlowLayout.RIGHT, FlowLayout.CENTER, and
FlowLayout.LEFT respectivley.

The FlowLayout manager is


part of the java.awt package.

76
FlowLayout Class

The constructors FlowLayout class

The get and set methods for these data fields are provided in
java.awt.FlowLayout the class, but omitted in the UML diagram for brevity.

-alignment: int The alignment of this layout manager (default: CENTER).


-hgap: int The horizontal gap of this layout manager (default: 5 pixels).
-vgap: int The vertical gap of this layout manager (default: 5 pixels).

+FlowLayout() Creates a default FlowLayout manager.


+FlowLayout(alignment: int) Creates a FlowLayout manager with a specified alignment.
+FlowLayout(alignment: int, hgap: Creates a FlowLayout manager with a specified alignment,
int, vgap: int) horizontal gap, and vertical gap.

77
77
FlowLayout
import javax.swing.*;
import java.awt.*;
public class ShowFlowLayout extends JFrame {
public ShowFlowLayout() {
// Set FlowLayout, aligned left with horizontal gap 10
// and vertical gap 20 between components
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
// Add labels and text fields to the frame
add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(1));
add(new JLabel("Last Name"));
add(new JTextField(8));
}

78
FlowLayout
public static void main(String[] args) {
ShowFlowLayout frame = new ShowFlowLayout();

frame.setTitle("ShowFlowLayout");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}

79
BorderLayout

• The BorderLayout manager divides the window into five areas:


East, South, West, North, and Center.
• At most five components can be added.
• If you want more components, add a Panel, then add components to
it.
• Components are added to a BorderLayout by using
add(Component, index) where index is a constant such as :
 BorderLayout.EAST
 BorderLayout.SOUTH
 BorderLayout.WEST
 BorderLayout.NORTH
 BorderLayout.CENTER

80
BorderLayout…

The get and set methods for these data fields are provided in
java.awt.BorderLayout the class, but omitted in the UML diagram for brevity.

-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).

+BorderLayout() Creates a default BorderLayout manager.


+BorderLayout(hgap: int, vgap: int) Creates a BorderLayout manager with a specified number of
horizontal gap, and vertical gap.

81
81
BorderLayout …
import javax.swing.*;
import java.awt.BorderLayout;
public class ShowFlowLayout extends JFrame {
public ShowFlowLayout() {
// Set BorderLayout with horizontal gap 5 and vertical
gap 10
setLayout(new BorderLayout(5, 10));

// Add buttons to the frame


add(new JButton("East"), BorderLayout.EAST);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("Center"), BorderLayout.CENTER);
}

82
BorderLayout…
public static void main(String[] args) {
ShowFlowLayout frame = new ShowFlowLayout();
frame.setTitle("ShowBorderLayout");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}

83
GridLayout
• The GridLayout manager divides the container up into a
given number of rows and columns:
new GridLayout(rows, columns)
• All sections of the grid are equally sized and as large as
possible

setLayout(new GridLayout(2, 3));


add(new Button(“one"));
add(new Button(“two"));
add(new Button(“three"));
add(new Button(“four"));
add(new Button(“five"));
add(new Button(“six"));
84
GridLayout…

The get and set methods for these data fields are provided in
java.awt.GridLayout the class, but omitted in the UML diagram for brevity.

-rows: int The number of rows in this layout manager (default: 1).
-columns: int The number of columns in this layout manager (default: 1).
-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).

+GridLayout() Creates a default GridLayout manager.


+GridLayout(rows: int, columns: int) Creates a GridLayout with a specified number of rows and columns.
+GridLayout(rows: int, columns: int, Creates a GridLayout manager with a specified number of rows and
hgap: int, vgap: int) columns, horizontal gap, and vertical gap.

85
85
GridLayout … example
import javax.swing.*;
import java.awt.GridLayout;
public class ShowGridLayout extends JFrame {
public ShowGridLayout() {

setLayout(new GridLayout(3, 2, 5, 5));

add(new JLabel("First Name"));


add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(1));
add(new JLabel("Last Name"));
add(new JTextField(8));
}
86
GridLayout example…
public static void main(String[] args) {
ShowGridLayout frame = new ShowGridLayout();
frame.setTitle("ShowGridLayout");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
frame.setSize(200, 125); frame.setVisible(true);
}
}

Output:

87
GridLayout …
 You can specify the number of rows and columns in the grid.
 The basic rules are as follows:
The number of rows or the number of columns can be zero.
But not both. If one is zero and the other is nonzero, nonzero dimension is fixed,
while the zero dimension is determined dynamically by the layout manager.

For example: if you specify three rows and zero columns for a grid that has ten
components, GridLayout creates three fixed rows of four columns, with the last
row contains two components.

88
GridLayout …
If both the number of rows and the number of columns are nonzero, the number of
rows is the dominating parameter; that is, the number of rows is fixed, and the
layout manager dynamically calculates the number of columns.

For example: if you specify three rows and three columns for a grid that has ten
components , GridLayout creates three fixed rows of four columns, with the last
row containing two components.

89
GridBagLayout
• GridBagLayout lays out components based on a grid with rows and columns that
need not all be the same size.
• GridBagLayout is the most sophisticated, flexible layout manager the Java
platform provides.
• For each component there are eleven constraint values.
• GridBagConstraint properties:

90
GridBagConstraint properties:
• int gridx ( >=0 ) :The column in which the component is placed (It starts at 0)
• int gridy(>= 0 ) :The row in which the component is placed (It starts at 0)
• int gridwidth (>= 1 ) :The number of columns the component occupies
• int gridheight( >=1 ) The number of rows the component occupies
• int fill : Specifies how the component is to be enlarged to fill its allocated region.
• Valid values are:
• GridBagConstraints.NONE – doesn’t resize the component (Default).
• GridBagConstraints.HORIZONTAL - make the component wide enough to fill
its display area horizontally, but don't change its height
• GridBagConstraints.VERTICAL - make the component tall enough to fill its
display area vertically, but don't change its width.
• GridBagConstraints.BOTH - make the component fill its display area entirely.
BoxLayout
• BoxLayout arranges components either horizontally or vertically in a panel.
• You can control alignment and spacing of the components.
• Complicated layouts can be made by combining many panels, some with
horizontal layout and some with vertical layouts.

92
Using Panels as Sub container
• When the user resizes the frame the layout of components can change drastically.
• FlowLayout does not keep related items together. It just puts them in the rows one after
another as they are added.
• This section discusses how to better control the layout process.
• One method for ensuring that a graphical interface looks the way you intend is
setResizable method of JFrame. So that you can prevent the user from resizing it.
public void setResizable(boolean resizable)
• If the parameter is false then the user cannot resize the frame.
• But this does not solve all problems. When a frame contains several logical groups of
components it may be difficult to lay them out correctly using a single layout manager.
• You would like to group related components together, and then to lay out the groups in the
frame. This is where panels are useful.

93
Using Panels as Sub container
• A JPanel is a container that is used to group components together.
• Panels do not have visible edges.
• To layout components using JPanels:
1. Decide on how to divide the frame into panels.
2. Add GUI components to panels .
3. Add the panels to the frame.
• Each panel has its own layout manager.
• The default layout manager of JPanel is Flowlayout, which is often ideal, but you may
use another layout manager if appropriate.
• When the panels are added to a frame, the frame's layout manager arranges the panels as
if each panel were a single component.

94
Adding Components to JPanels

• You can use new JPanel() to create a panel with the default FlowLayout manager or new
JPanel(LayoutManager) to create a panel with the specified layout manager.

• Use the Add(Component c) method to add a component to the panel.

• You need to say which container (which panel) gets each component.

Syntax: whichPanel.add(ComponentObjectRefVar);

• means run the add() method of whichPanel to add the object to that panel.

95
Adding Components to JPanels
For example:- The following code creates a panel and adds a button to it.
JPanel p = new JPanel();
p.add(new JbButton(“OK”));
• Panels can be placed inside a frame or inside another panel.
JFrame f = new JFrame();
JPanel p = new JPanel();
f.add(p);
JPanel p1 = new JPanel();
JPanel p = new JPanel();
p1.add(p);
f.add(p1);

96
Adding Components to JPanels
• The default layout manager, for JPanel is FlowLayout, so
setLayout() does not need to be called.
Example 1: Create a window which looks like the following:

97
Adding Components to JPanels
1.Create Components 2.Create Panels
JLabel lb1 = new JLabel("Percent of Calories from Fat"); JPanel p1 = new JPanel();
Jlabel lbl2 = new JLabel("Enter grams of fat: "); JPanel p2 = new JPanel();
Jlabel lbl3 = new JLabel("Enter total calories: "); Jpanel p3 = new JPanel();
Jlabel lbl4 = new JLabel("Percent calories from fat: "); JPanel p4 = new JPanel();
JTextField txt1 = new JTextField( 7 ); JPanel p5 = new JPanel();
JTextField txt2 = new JTextField( 7 ); 3.Add Components to Panel
p1.add( lb1 );
JTextField txt3 = new JTextField( 7 ); 4.Add Panel into the Frame
p2.add( lbl2 );
p2.add( txt1 ); setLayout( new FlowLayout());
JButton jbt1 = new JButton("Do It!");
p3.add( lbl3 ); add( p1 );
p3.add( txt2 ); add( p2 );
p4.add( lbl4 ); add( p3 );
p4.add( txt3); add( p4 );
p5.add( jbt1 );
add( p5 );

98
Adding Components to JPanels
Example 2: Create a window which looks like the following:
1.Create Components
JLabel lData1 = new JLabel("Data Item 1");
JLabel lData2 = new JLabel("Data Item 2");
JLabel lData3 = new JLabel("Data Item 3");
JTextField txData1 = new JTextField( 7 );
JTextField txData2 = new JTextField( 7 );
JTextField txData3 = new JTextField( 7 );
2.Create Panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
4.Add Panel into the Frame 3. Add Components to Panel
setLayout( new FlowLayout()); panel1.add( lData1 );
panel1.add( txData1 );
add( panel1 ); panel2.add( lData2 );
panel2.add( txData2 );
add( panel2 ); panel3.add( lData3 );
panel3.add( txData3 );
add( panel3 ); 99
Adding Components to JPanels
Exercise : Create a window which looks like the
following:

100
Adding Components to JPanels

BoxLayout
• Sometimes you want components to be lined up in a
strictly vertical (or strictly horizontal) order. This can
be done with a BoxLayout layout manager.
• Here is a constructor for it:
BoxLayout(Container contain, int axis)
contain: the container this layout manager is for
axis: BoxLayout.X_AXIS — for left to right alignment
BoxLayout.Y_AXIS — for top to bottom
alignment
101
Adding Components to JPanels
• Notice that the constructor needs a reference to the container that it
is managing.
• To set the layout manager of a JPanel to BoxLayout with vertical
alignment, do this:
JPanel panel = new JPanel();
panel.setLayout( new BoxLayout( panel, BoxLayout.Y_AXIS) );

102
Adding Components to JPanels
Example 1 : Create a window which looks like the following:

103
Adding Components to JPanels

• Add components into the panel


panel1.add( lData1 ); panel1.add( txData1 );
panel2.add( lData2 ); panel2.add( txData2 );
panel3.add( lData3 ); panel3.add( txData3 );
panel4.add( lData4 ); panel4.add( txData4 );
panel5.add( lData5 ); panel5.add( txData5 );
panel6.add( lData6 ); panel6.add( txData6 );

104
Adding Components to JPanels
• Set layout manager for left panel, add three small panels to it:

pnLeft.setLayout( new BoxLayout( pnLeft, BoxLayout.Y_AXIS )


);
pnLeft.add ( panel1 );
pnLeft.add( panel2 );
pnLeft.add ( panel3 );

105
Adding Components to JPanels
• Set layout manager for right panel, add three small panels to it:
pnRight.setLayout( new BoxLayout( pnRight, BoxLayout.Y_AXIS )
);
pnRight.add( panel4);
pnRight.add( panel5);
pnRight.add( panel6);

106
Adding Components to JPanels
• Add left and right panels to the frame

setLayout( new FlowLayout() );


add( pnLeft );
add( pnRight );

107
Example
• Layout Managers can be used together
import java.awt.*;
import javax.swing.*;
public class TestPanels extends JFrame {
public TestPanels() {
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4, 3));
for (int i = 1; i <= 9; i++)
p1.add(new JButton("" + i));
p1.add(new JButton("" + 0));
p1.add(new JButton("Start"));
p1.add(new JButton("Stop"));
JPanel p2 = new JPanel(new BorderLayout());
p2.add(new JTextField("Time to be displayed here"), BorderLayout.NORTH);
108
Example
p2.add(p1, BorderLayout.CENTER);
add(p2, BorderLayout.EAST);
add(new JButton("Food to be placed here"),
BorderLayout.CENTER);
}
public static void main(String[] args) {
TestPanels frame = new TestPanels();
frame.setTitle("The Front View of a Microwave Oven");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 250);
frame.setVisible(true);
}
}
109
Jpanel…
import java.awt.*;
import javax.swing.*;
public class MainClass extends JFrame {
private JPanel buttonJPanel; // panel to hold buttons
private JButton buttons[]; // array of buttons
public MainClass(){ // no-argument constructor
super( "Panel Demo" );
buttons = new JButton[ 5 ]; // create buttons array
buttonJPanel = new JPanel(); // set up panel
buttonJPanel.setLayout( new GridLayout( 1, buttons.length
) );
for (int i=0;i<buttons.length;i++){
buttons[i] = new JButton("Button "+(i+1));
buttonJPanel.add( buttons[i]);
add( buttonJPanel, BorderLayout.SOUTH );
} // end PanelFrame constructor
} // end class PanelFrame
110
}
JPanel…
class PanelDemo extends JFrame {
public static void main( String args[] ){
MainClass panelFrame = new MainClass();
panelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
panelFrame.setSize( 450, 200 ); // set frame size
panelFrame.setVisible( true ); // display frame
}
}

111

You might also like