Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 1 GUI

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 145

Object-Oriented Programming

Chapter 5 (1): GUI in Java


1
Agenda
Introduction
• Layeout Mangement
Simple GUI-Based IO
• FlowLoyout
with JOptionPane.
AWT vs swing
• BorderLayout
• GridLayout
Containers and
• ….
Components
Introduction to
Components
Jlable
Jbotton
…
2
Introduction
A graphical user interface (GUI) presents a user-
friendly mechanism for interacting with an application.

It gives an application a distinctive “look” and “feel.”


Providing different applications with consistent,
intuitive user interface components allows users to be
somewhat familiar with an application, so that they can
learn it more quickly and use it more productively.
GUIs are built from GUI components. These are
sometimes called controls or widgets—short for
window gadgets—in other languages.
A GUI component is an object with which the user
3
interacts via the mouse, the keyboard or another form
Introduction
A GUI component is an object with which the user
interacts via the mouse, the keyboard or another form
of input, such as voice recognition.
In this chapter you will earn about many of Java’s
GUI components.

4
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 firstNumber =
JOptionPane.showInputDialog( "Enter first integer" );
int number1 = Integer.parseInt( firstNumber );
String secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
int number2 = Integer.parseInt( secondNumber );
int sum = number1 + number2; // add numbers
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );
5 }
}
Simple GUI-Based …
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.
6
 It can also be used to specify that the dialog should appear
centered over a particular window of the computer screen.
Simple GUI-Based…
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
7
showMessageDialog, as well as methods that display
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
AWT uses the native operating system's window
routines so the visual effect is dependent on the run-
8
time system platform.
AWT vs Swing
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.
AWT is adequate for many applications but it is
difficult to build an attractive GUI
9
AWT vs Swing
Swing is designed to solve AWT’s problems (present
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
10
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
Actually, you can, but it’s tricky and not worth doing
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.)

11 AWT classes are contained inside package java.awt
while swing classes are located in package javax.swing.
GUI Class Hierarchy

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 Swing Components


in the javax.swing package

Lightweight

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

13
GUI 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
14 container that includes a panel.
GUI Classes…
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.

15
Container 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
Container classes can contain other
GUI components.
Lightweight

16 16
GUI 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.

17
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


18 18
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)
19
Color chooser (JColorChooser)
Swing GUI Components …
More complex displays
Tables (JTable)
Trees (JTree)
Formatted Text

Every GUI components has


Properties

Methods JButton

Events

20
GUI Class…
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
21
colors of lines, shapes,…..
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.

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,
22
TextField, TextArea). The AWT is helper classes remain
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
23 23
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.
24
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.
25
Creating a Frames

26
Frame

The JFrame class can be used to create windows.

For Swing GUI programs, use JFrame class to create


widows.

27
 

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.

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

29 29
JFrames…
JFrame
public Class
void Methods
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
the number of pixels from the left of the screen and y is
is the
number from the top of the screen. height and width are
as
30
before.
30
JFrames…
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:

• JFrame.EXIT_ON_CLOSE:- Exit the application.

• JFrame.HIDE_ON_CLOSE:- Hide the frame, but keep the application running.

• JFrame.DO_NOTHING_ON_CLOSE:- Ignore the click.

31 31
JFrame…
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);
}
}

32
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
33
the frame on the screen.
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.
34
JFrame…
import javax.swing.JFrame;
public class Simple extends JFrame {
public Simple() {
setSize(300, 200);
setTitle("First JFrame");
setLocationRelativeTo(null);
SetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
Simple simple = new Simple();

}
}

35
JFrame…

• The setTitle(String text) method is defined in


the
java.awt.Frame class.

• Since JFrame is subclass of Frame, you can use it to se


a title
for an object of JFrame.

• The constructor Simple() does not explicitly invoke


the constructor JFrame(). But the constructor JFrame()
is
36
invoked implicitly. (Constructor Chaining).
Adding Components into a Frame

37
GUI Components
 Introduces the frequently used GUI components

JButton
Component Container JComponent AbstractButton JCheckBox
JToggleButton
JLabel JRadioButton
JTextArea

JTextComponent
JTextField JPasswordField
JComboBox

JList

JScrollBar

JSlider

38 38
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
39 39
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.

40 40
JButton
The following are JButton constructors:
JButton()
Creates a default button with no text and icon.

JButton(Icon icon)
Creates a button with an icon.

JButton(String text)
Creates a button with text.

JButton(String text, Icon icon)


Creates a button with text and an icon.
41 41
JButton
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.AbstractButton
-actionCommand: String The action command of this button.
-text: String The button’s text (i.e., the text label on the button).
-icon: javax.swing.Icon The button’s default icon. This icon is also used as the "pressed" and
"disabled" icon if there is no explicitly set pressed icon.
-pressedIcon: javax.swing.Icon The pressed icon (displayed when the button is pressed).
-rolloverIcon: javax.swing.Icon The rollover icon (displayed when the mouse is over the button).
-mnemonic: int The mnemonic key value of this button. You can select the button by
pressing the ALT key and the mnemonic key at the same time.
-horizontalAlignment: int The horizontal alignment of the icon and text (default: CENTER).
-horizontalTextPosition: int The horizontal text position relative to the icon (default: RIGHT).
-verticalAlignment: int The vertical alignment of the icon and text (default: CENTER).
-verticalTextPosition: int The vertical text position relative to the icon (default: CENTER).
-borderPainted: boolean Indicates whether the border of the button is painted. By default, a regular
button’s border is painted, but the borders for a check box and a radio
button is not painted.
-iconTextGap: int The gap between the text and the icon on the button (JDK 1.4).
-selected(): boolean The state of the button. True if the check box or radio button is selected,
42 42 false if it's not.
JButton
JButton Properties

text

icon

mnemonic

horizontalAlignment

verticalAlignment

horizontalTextPosition

verticalTextPosition

iconTextGap
43 43
JButton
Some Useful JButton Methods

public void setText(String text)


Sets the button's text.

public String getText()


 Returns the button's text.

public void setEnabled(boolean b)


Enables (or disables) the button.
44
JButton
Some useful JButton Methods

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.

45
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)
46 +JLabel(text:
46 String, hAlignment: int) Creates a label with text and the specified horizontal alignment.
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 an text and the specified horizontal
alignment.

47 47
JLabel

The constructors for labels are as follows:

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

49 49
JLabel Jlabel…
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
50
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);

51 51
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.
 The program can write the results of a calculation to a
Text Field.
 Text fields are useful in that they enable the user to
enter in
variable data (such as a name or a description).
 JTextField is swing class for an editable text display.

52 52
JTextField

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.

53 53
JTextField

JTextField Constructors:

JTextField(int columns)
Creates an empty text field with the specified number of
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.
54 54
JTextField
JTextField Properties
text
horizontalAlignment
editable
columns

55 55
JTextField
JTextField Methods

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.
56 56
JTextField
JTextField Methods
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(Stringvalue)


Appends the text value of the string to the already
existing text in the component
57 57
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);

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

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

59
JPasswordField…
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
60 and columns.
JPasswordField….

JLabel lb = new JLabel(“Password”);


JPasswordField password = new JPasswordField(10
);

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

62 62
JTextArea….
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 colu
+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.

63 63
JTextArea….
JTextArea Constructors

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 and
the number of rows and columns specified.

64 64
JTextArea….
JTextArea Properties:
text
editable
columns
lineWrap
wrapStyleWord
rows
lineCount
tabSize

65 65
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);

66
JTextArea…

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


68 68
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 chec
selected: boolean) box is initially selected.

69 69
 

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.
70
JCheckBox …
JCheckBox Constructor Summary

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.

71
JCheckBox…

JCheckBox red = new JCheckBox(“Red”, true);


JCheckBox blue = new JCheckBox(“Blue”);
JCheckBox green = new JCheckBox(“Green”);
JCheckBox yellow = new JCheckBox(“Yellow”);
72
JRadioButton
Radio buttons are variations of check boxes. They are
often used in the group, where only one button is
checked at a time.

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

74 74
JRadioButton

JRadioButton bird = new JRadioButton("Bird");
JRadioButton cat = new JRadioButton("Cat");
JRadioButton dog = new JRadioButton("Dog");
add(bird);
add(cat);
add(dog);
75
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);
76
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.

77 77
JList…
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.
78 +setSelectionMode(selectionMode:
78 int): Sets the selection mode for the list.
JList…

JList Constructors

 JList(): Creates an empty list.


 JList(Object[] stringItems)

Creates a new list initialized with items.

79 79
JList…
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.
80
80
JList…
Jlist Methods

Object[] getSelectedValues()
 Returns an array of the values for the selected cells.  

 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.

81 81
JList…
Jlist Methods

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
82
selected
82 item.
JList…

JList Properties

selectedIndexd
selectedIndices
selectedValue
selectedValues
selectionMode
visibleRowCount

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

84
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.
85 85
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.
86 86
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.
87 87
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);

88
Menu Components

89
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);
   
  }
}
90
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
91
the content pane’s add method to place a component
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.

92
Adding Components into a
// Add
Frame
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

93 93
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
frame.add(new JButton("OK"));
94 94
Adding Components into a
import javax.swing.*; Frame
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
}
}
95
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);

96
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.
97
Layout Management
Layouts tell Java where to put components in
containers (JPanel, content pane, etc).
Layout manager is created using layout manager 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,


98
but it's better to set the layout explicitly for clarity.
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

99
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

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

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

102 102
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));
}
103
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);
}
}

104
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
105
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.

106 106
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);
107 }
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);
}
}

108
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"));
109
add(new Button(“six"));
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.

110 110
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));
111
}
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:

112
GridLayout …
You can specify the number of rows and columns in the
grid.
The basic rules are as follows:
I. 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,
GrideLayout creats three fixed rows of four columns,
113
with the last row contains two components.
GridLayout …

II. 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.
114
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

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

116
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.
117
public void setResizable(boolean
Using Panels as Sub container
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.

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


119
Using Panels as Sub container
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.

120
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
121
object to that panel.
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();
122
p1.add(p);
f.add(p1);
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:

123
Adding Components to JPanels
Create Components
JLabel lb1 = new JLabel("Percent of Calories from Fat");
Jlabel lbl2 = new JLabel("Enter grams of fat: ");
Jlabel lbl3 = new JLabel("Enter total calories: ");
Jlabel lbl4 = new JLabel("Percent calories from fat: ");

JTextField txt1 = new JTextField( 7 );


JTextField txt2 = new JTextField( 7 );
JTextField txt3 = new JTextField( 7 );

JButton jbt1 = new JButton("Do It!");


124
Adding Components to JPanels
Create Panels

JPanel p1 = new JPanel();


JPanel p2 = new JPanel();
Jpanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();

125
Adding Components to JPanels
Add Components to Panel
p1.add( lb1 );

p2.add( lbl2 );
p2.add( txt1 );

p3.add( lbl3 );
p3.add( txt2 );

p4.add( lbl4 );
p4.add( txt3);

126 p5.add( jbt1 );


Adding Components to JPanels
Add Panel into the Frame
setLayout( new FlowLayout());

add( p1 );
add( p2 );
add( p3 );
add( p4 );
add( p5 );

127
Adding Components to JPanels
Example 2: Create a window which looks like the
following:

128
Adding Components to JPanels
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 );

129
Adding Components to JPanels
Create Panels

JPanel panel1 = new JPanel();


JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();

130
Adding Components to JPanels
Add Components to Panel

panel1.add( lData1 );
panel1.add( txData1 );

panel2.add( lData2 );
panel2.add( txData2 );

panel3.add( lData3 );
panel3.add( txData3 );

131
Adding Components to JPanels
Add Panel into the Frame

setLayout( new FlowLayout());

add( panel1 );
add( panel2 );
add( panel3 );

132
Adding Components to JPanels
Exercise : Create a window which looks like the
following:

133
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
134 alignment
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) );

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

136
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 );

137
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 );

138
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);

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

setLayout( new FlowLayout() );


add( pnLeft );
add( pnRight );

140
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);
141
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);
}
}
142
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
143
}
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
}
}

144
Reading Assignment
Constructors and Methods of all
components and Layout Managers
discussed in this lecture

145

You might also like