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

07-GUI

The document provides an overview of Java GUI development using Swing and AWT, detailing the structure of GUI applications with components and containers. It discusses various layout managers like BorderLayout, FlowLayout, GridLayout, and GridBagLayout, along with examples of how to implement them in Java code. Additionally, it covers event-oriented programming concepts, including event sources, listeners, and specific event types such as ActionEvent and MouseEvent.

Uploaded by

dhuy250905
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

07-GUI

The document provides an overview of Java GUI development using Swing and AWT, detailing the structure of GUI applications with components and containers. It discusses various layout managers like BorderLayout, FlowLayout, GridLayout, and GridBagLayout, along with examples of how to implement them in Java code. Additionally, it covers event-oriented programming concepts, including event sources, listeners, and specific event types such as ActionEvent and MouseEvent.

Uploaded by

dhuy250905
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

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.
• javax.swing 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 javax.swing.JFrame ;

public class ContainerDemo {


public static void main(String[] args) {
JFrame jframe1 = new JFrame();
jframe1.setSize(300, 200);
jframe1.setTitle("This is a frame");
jframe1.setVisible(true);
}
}
example
• Create frame and button

package container;

import javax.swing.JButton;
import javax.swing.JFrame;

public class ContainerDemo {


public static void main(String[] args) {
JFrame jframe1 = new JFrame();

JButton jbutton1 = new JButton("Test container");


jframe1.add(jbutton1);// thêm button vào JFrame

jframe1.setSize(300, 200);
jframe1.setTitle("This is a frame");
jframe1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe1.setVisible(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:
Container.add ("East", component);
Container.add ( BorderLayout.EAST ,
component);

• Same for “West”, “South”, “North”, “Center”


BorderLayout
BorderLayout
package container;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;

public class BorderLayoutDemoFrame extends JFrame{


public BorderLayoutDemoFrame() {
this.getContentPane().add(BorderLayout.NORTH, new JButton("NORTH"));
this.getContentPane().add(BorderLayout.SOUTH, new JButton("SOUTH"));
this.getContentPane().add(BorderLayout.CENTER, new
JButton("CENTER"));
this.getContentPane().add(BorderLayout.WEST, new JButton("WEST"));
this.getContentPane().add(BorderLayout.EAST, new JButton("EAST"));
}

public static void main(String[] args) {


BorderLayoutDemoFrame frame = new BorderLayoutDemoFrame();

frame.setSize(400, 300);
frame.setTitle("Border layout demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(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 javax.swing.JButton ;
import javax.swing.JFrame ;
import javax.swing.JPanel ;
import javax.swing.JTextField ;

public class FlowLayoutDemo extends JFrame {


public FlowLayoutDemo () {
JPanel panel1 = new JPanel();
panel1.add(new JTextField(10));
panel1.add(new JButton("Sample"));
panel1.add(new JButton("Sample2"));
getContentPane().add(panel1);
}

public static void main(String[] args) {


FlowLayoutDemo frame = new FlowLayoutDemo();

frame.setSize(400, 300);
frame.setTitle("Flow layout demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
GridLayout
• Arrange components in a grid
GridLayout
package container;

import java.awt.GridLayout ;

import javax.swing.JButton ;
import javax.swing.JFrame ;
import javax.swing.JPanel ;

public class GridLayoutDemo extends JFrame {


public GridLayoutDemo() {
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(3, 3));

for (int i = 0; i < 9; i++) {


panel1.add(new JButton(String.valueOf(i)));
}
getContentPane().add(panel1);
}

public static void main(String[] args) {


GridLayoutDemo frame = new GridLayoutDemo();

frame.setSize(400, 300);
frame.setTitle("Flow layout demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(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: GridBagConstraints.NORTH, 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: GridBagConstraints.NONE,
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 java.awt.GridBagConstraints ;
import java.awt.GridBagLayout ;

import javax.swing.JButton ;
import javax.swing.JFrame ;

public class GridBagLayoutDemo extends JFrame{


public GridBagLayoutDemo() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
add(new JButton("b1"), c);
c.gridx = 1;
add(new JButton("b2"), c);
c.gridx = 2;
GridBagLayout
add(new JButton("b3"), c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;

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();
frame1.setVisible(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();
c.gridx = 0; c.gridy = 0; c.weighty = 0.3;
add(new JButton("b1"), c);
c.gridx = 1;
add(new JButton("b2"), c);
c.gridx = 2;
add(new JButton("b3"), c);
c.gridx = 0; c.gridy = 1; c.gridwidth = 2;
c.weighty = 0.7;
c.fill = GridBagConstraints.BOTH;
add(new JButton("b4"), c);
c.gridx = 2; c.gridwidth = 1;
add(new JButton("b5"), c);

practice
• Create layout as sample

GridBagLayout

GridLayout

BorderLayout.South
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());
buttonGreen.addActionListener(this);
add(buttonGreen);
buttonRed.addActionListener(this);
add(buttonRed);
buttonBlue.addActionListener(this);
add(buttonBlue);

setSize(400, 300);
setTitle("Change background demo");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
example
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(buttonGreen)) {
getContentPane().setBackground(Color.GREEN);
}
else if(e.getSource().equals(buttonBlue)) {
getContentPane().setBackground(Color.BLUE);
}
else if(e.getSource().equals(buttonRed)) {
getContentPane().setBackground(Color.RED);
}
}
public static void main(String[] args) {
EventDemoFrame frame = new EventDemoFrame();
frame.setVisible(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
• https://viettuts.vn/java-swing
• https://viettuts.vn/java-awt/cac-lop-adapter-trong-java-awt
• http://www.netfoo.net/oreilly/java/javanut/figs/jn2_2001.gif

You might also like