JAVA TECHNOLOGY
Chapter 7
GUI in Java with AWT - SWING
Concept
component container
GUI = Containers + Components
Java Swing
• Java Swing is a part of Java Foundation Classes (JFC)
used to create window-based applications. It is built on
the API AWT (Abstract Windowing Toolkit) and is
written entirely in Java.
• Unlike AWT, Java Swing provides platform-independent
and lightweight components.
• [Link] package provides classes for java swing API
like JButton, JTextField, JTextArea, JRadioButton,
JCheckbox, JMenu, JColorChooser…
Java swing
Putting components into the GUI
• Create a suitable component object.
• Defines the initial appearance of the component.
• Locate this component on the GUI.
• Add this component to the GUI.
Putting components into the GUI
• example
2 labels
2 text fields container
1 button
Container
Container
Component
Container
Panel Window
Applet Frame Dialog
Container
frame
Frame is a rectangular frame
with a border and window
control buttons
Panel
Panel without border
Concept
• Container: Object that contains elements, allowing
drawing and coloring on the container.
• Frame and Panel are commonly used classes.
• Panels are often used to contain elements in a
complex GUI, a Frame can contain many Panels .
• Applet is often used to create an application
embedded in the Browser.
example
• Create frame:
package container;
import [Link] ;
public class ContainerDemo {
public static void main(String[] args) {
JFrame jframe1 = new JFrame();
[Link](300, 200);
[Link]("This is a frame");
[Link](true);
}
}
example
• Create frame and button
package container;
import [Link];
import [Link];
public class ContainerDemo {
public static void main(String[] args) {
JFrame jframe1 = new JFrame();
JButton jbutton1 = new JButton("Test container");
[Link](jbutton1);// thêm button vào JFrame
[Link](300, 200);
[Link]("This is a frame");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
Layout
• Layout: How to arrange components on the container.
• It is not easy to manually manage the placement of
components on the GUI.
• LayoutManager is an interface that describes layouts.
• Java provides a number of layouts, and these layout
classes all implement the LayoutManager interface.
BorderLayout
• Arrange the components along the border of the frame
to create 5 positions: EAST, WEST, SOUTH, NORTH,
CENTER
• This is the DEFAULT layout of the Frame.
• If the container has only 1 component and it is placed in
the CENTER position, this component will cover the
container.
• Syntax to add a component to a container at a location:
[Link] ("East", component);
[Link] ( [Link] ,
component);
• Same for “West”, “South”, “North”, “Center”
BorderLayout
BorderLayout
package container;
import [Link];
import [Link];
import [Link];
public class BorderLayoutDemoFrame extends JFrame{
public BorderLayoutDemoFrame() {
[Link]().add([Link], new JButton("NORTH"));
[Link]().add([Link], new JButton("SOUTH"));
[Link]().add([Link], new
JButton("CENTER"));
[Link]().add([Link], new JButton("WEST"));
[Link]().add([Link], new JButton("EAST"));
}
public static void main(String[] args) {
BorderLayoutDemoFrame frame = new BorderLayoutDemoFrame();
[Link](400, 300);
[Link]("Border layout demo");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
FlowLayout
• Arrange components in a flowing fashion in the order
in which they are added to the container.
• This is the default layout of the Panel.
• If there are multiple components on the container ->
Components can be placed on multiple lines ->
Alignment issue
• Between components, they have vertical gaps (vgap)
and horizontal gaps (hgap)
FlowLayout
FlowLayout
package container;
import [Link] ;
import [Link] ;
import [Link] ;
import [Link] ;
public class FlowLayoutDemo extends JFrame {
public FlowLayoutDemo () {
JPanel panel1 = new JPanel();
[Link](new JTextField(10));
[Link](new JButton("Sample"));
[Link](new JButton("Sample2"));
getContentPane().add(panel1);
}
public static void main(String[] args) {
FlowLayoutDemo frame = new FlowLayoutDemo();
[Link](400, 300);
[Link]("Flow layout demo");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
GridLayout
• Arrange components in a grid
GridLayout
package container;
import [Link] ;
import [Link] ;
import [Link] ;
import [Link] ;
public class GridLayoutDemo extends JFrame {
public GridLayoutDemo() {
JPanel panel1 = new JPanel();
[Link](new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
[Link](new JButton([Link](i)));
}
getContentPane().add(panel1);
}
public static void main(String[] args) {
GridLayoutDemo frame = new GridLayoutDemo();
[Link](400, 300);
[Link]("Flow layout demo");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
GridBagLayout
• Grid layout allows a component to occupy a
number of adjacent cells in both directions.
• How to put components in GridBagLayout:
– Placing a component in a position but spanning
multiple adjacent cells is a “constraint” of a
component to these cells.
– An object of the GridBagConstraints class will take
care of this.
GridBagLayout - GridBagConstraints
Properties :
• gridx, gridy : coordinates of the cell where the component will be placed
• gridwidth, gridheight : number of cells that will cover in 2 dimensions
when adding a component to the cell <gridx,gridy>
• weightx, weighty: Grid spacing, default is 0.
• anchor: Position of the component, default is CENTER, pre-declared
constants: [Link], EAST, WEST, SOUTH, NORTHEAST,
SOUTHEAST, NORTHWEST, SOUTHWEST.
• fill: Specifies the placement style when the component is larger than the
cell it will be placed in. Pre-declared constants: [Link],
HORIZONTAL, VERTICAL, BOTH.
• insets: Specifies the spacing <top, bottom, left, right> between the
inserted elements, default is 0.
• ipadx, ipady: The padding (number of empty pixels) inside the element in
2 dimensions. Defaults to 0. When drawing an element, 2*ipadx and
2*ipady will be added to the element's minimum width and minimum
height.
GridBagLayout
GridBagLayout
package container;
import [Link] ;
import [Link] ;
import [Link] ;
import [Link] ;
public class GridBagLayoutDemo extends JFrame{
public GridBagLayoutDemo() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
[Link] = 0;
[Link] = 0;
add(new JButton("b1"), c);
[Link] = 1;
add(new JButton("b2"), c);
[Link] = 2;
GridBagLayout
add(new JButton("b3"), c);
[Link] = 0;
[Link] = 1;
[Link] = 2;
[Link] = [Link];
add(new JButton("b5"), c);
setSize(400, 300);
//hien thi giua man hinh
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
GridBagLayoutDemo frame1 = new GridBagLayoutDemo();
[Link](true);
}
}
GridBagLayout
• To make the grid take up the entire space of the container, set
weights and weight > 0 weights and weight have a relative ratio
between rows/columns
GridBagLayout
…
GridBagConstraints c = new GridBagConstraints();
[Link] = 0; [Link] = 0; [Link] = 0.3;
add(new JButton("b1"), c);
[Link] = 1;
add(new JButton("b2"), c);
[Link] = 2;
add(new JButton("b3"), c);
[Link] = 0; [Link] = 1; [Link] = 2;
[Link] = 0.7;
[Link] = [Link];
add(new JButton("b4"), c);
[Link] = 2; [Link] = 1;
add(new JButton("b5"), c);
…
practice
• Create layout as sample
GridBagLayout
GridLayout
[Link]
Event Oriented Programming
Event
• Event: a signal that the application recognizes a
change in the state of an object.
• 3 sources of events:
(1) User (types a key, clicks an element,...)
(2) System (scheduling a task)
(3) Another event (events trigger each other)
• Nowadays, most languages provide this model, VC++
provides MFC (Microsoft Foundation Classes), Java
provides JFC (Java Foundation Classes).
Event handling
• When one the case happen out treat reason depending belong
enter People Okay commission waterfall the case
• Wallet example :When we (event source) are sick will release born
million event
– We have body arrive examination much uncle listener
– Each uncle officer will treat reason event handler way other each other
based on above million event
Event Listener 1
Process reason sick
( Uncle Doctor 1)
(event handler)
Event source Event
( Person ) ( Million
sick ) evidence )
Event Listener 2
( Uncle Doctor 2) Process reason sick
(event handler)
Concept
• Event: Is the event case release born when an object has changed
state.
• Event handler: Is the code that determines the application's
response when an event occurs.
• Event source: The object that triggers the event (for example, the
command button that the user clicks).
• Listener: An object that receives the delegation of event handling
to another object.
• Java defines Listener Interfaces for different situations (each Event
object has a corresponding Listener interface).
• A class that has listener capabilities will have to specify - code -
some behavior to handle an appropriate event.
example
example
…
public class EventDemoFrame extends JFrame implements
ActionListener {
JButton buttonGreen = new JButton("Green");
JButton buttonBlue = new JButton("Blue");
JButton buttonRed = new JButton("Red");
public EventDemoFrame() {
setLayout(new FlowLayout());
[Link](this);
add(buttonGreen);
[Link](this);
add(buttonRed);
[Link](this);
add(buttonBlue);
setSize(400, 300);
setTitle("Change background demo");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
example
@Override
public void actionPerformed(ActionEvent e) {
if([Link]().equals(buttonGreen)) {
getContentPane().setBackground([Link]);
}
else if([Link]().equals(buttonBlue)) {
getContentPane().setBackground([Link]);
}
else if([Link]().equals(buttonRed)) {
getContentPane().setBackground([Link]);
}
}
public static void main(String[] args) {
EventDemoFrame frame = new EventDemoFrame();
[Link](true);
}
}
}
Events
Events
• Components will generate different events
• Each event will be handled by a corresponding
listenerListener is an interface
• Adapter defaults the methods of Listener.
• If you extend Adapter, you will not need to provide
implementation for all the methods of the Listener interface
-> code savings
Action Event
• An ActionEvent object is generated when: a command
button is clicked, a list item is double-clicked, a menu item is
clicked.
• Constants to check if a key is pressed when clicking the
mouse: ALT_MASK (Alt key), CTRL_MASK (Ctrl key),
SHIFT_MASK (Shift key).
Adjustment Event
• Generated when a scroll bar is manipulated.
• Constants BLOCK_DECREMENT, BLOCK_INCREMENT: Block
decrement/increment when the user clicks on the area
between the slider and an edge of the scroll bar,
UNIT_DECREMENT, UNIT_INCREMENT: Unit
decrement/increment when the user clicks on the arrows at
both ends of the scroll bar. TRACK: Value describing the scroll
bar when the user drags
Container Event
• Generated when a component is added/removed from a
container.
• Event description constants: COMPONENT_ADDED,
COMPONENT_REMOVED.
Component Event
• Generated when a component is hidden, shown, moved, or
resized.
• The constants describing the state include :
– COMPONENT _ HIDDEN,
– COMPONENT _ MOVED,
– COMPONENT _RESIZED ,
– COMPONENT _SHOWN
Input Event
• Is the parent class of 2 child classes: KeyEvent and
MouseEvent.
• The constants declared in this class describe the keystroke
mask bits associated with the event or which mouse button
was pressed: ALT_MASK, CTRL__MASK, META_MASK,
SHIFT_MASK, BUTTON1_MASK, BUTTON2_MASK,
BUTTON3_MASK.
Key Event
• Generated when user operates on keyboard.
• The constants are intKEY_PRESSED, KEY_RELEASED,
KEY_TYPED. If a letter or number key is pressed, all three
types of events are generated (pressed, released, typed). If
a special key is pressed (Home, End, PageUp, PageDown-
modifier key), only two events are generated: pressed,
released.
Mouse Event
• Generated when the user mouses over a component.
• constants int:
– MOUSE _CLICKED ,
– MOUSE _DRAGGED ,
– MOUSE _ENTERED ,
– MOUSE _EXITED ,
– MOUSE _MOVED ,
– MOUSE _PRESSED ,
– MOUSE _RELEASED.
Text Event
• Raised when characters in a TextField or a textArea are
changed.
• Constant int: TEXT_VALUE_CHANGED
Reference
• [Link]
• [Link]
• [Link]