Java Absolute Layout (AbsoluteLayout) – Example สำหรับ AbsoluteLayout เป็นการจัดวาง Layout ในรูปแบบของ X,Y โดยอ้างตำแหน่งของ Controls จากตำแหน่งต่าง ๆ ที่อยู่ใน Frame จากแกน X และแกน Y ซึ่งทุก ๆ Controls ที่สร้างขึ้นจะต้องมีตำแหน่ง X,Y เป็นตัวระบุตำแหน่งด้วย และสามารถจัดวางได้อย่างอีสระ ซึ่ง Layout นี้จะได้รับความนิยมมากที่สุด เพราะสามารถใช้งานได้ง่าย

Java Absolute Layout (AbsoluteLayout) – Example
Syntax
1.
getContentPane().setLayout(
null
);
// ค่าของ AbsoluteLayout จะใช้ null
2.
3.
JButton btn1 =
new
JButton(
"Button 1"
);
4.
btn1.setBounds(
41
,
29
,
89
,
23
);
// (x,y,height,width)
Component Control ของ Layout
Example
MyForm.java
01.
package
com.java.myapp;
02.
03.
import
java.awt.EventQueue;
04.
05.
import
javax.swing.JButton;
06.
import
javax.swing.JFrame;
07.
08.
public
class
MyForm
extends
JFrame {
09.
10.
/**
11.
* Launch the application.
12.
*/
13.
public
static
void
main(String[] args) {
14.
EventQueue.invokeLater(
new
Runnable() {
15.
public
void
run() {
16.
MyForm frame =
new
MyForm();
17.
frame.setVisible(
true
);
18.
}
19.
});
20.
}
21.
22.
/**
23.
* Create the frame.
24.
*/
25.
public
MyForm() {
26.
27.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
28.
setBounds(
100
,
100
,
450
,
300
);
29.
setTitle(
"ThaiCreate.Com GUI Tutorial"
);
30.
31.
getContentPane().setLayout(
null
);
32.
33.
JButton btn1 =
new
JButton(
"Button 1"
);
34.
btn1.setBounds(
41
,
29
,
89
,
23
);
35.
getContentPane().add(btn1);
36.
37.
JButton btn2 =
new
JButton(
"Button 2"
);
38.
btn2.setBounds(
206
,
50
,
89
,
23
);
39.
getContentPane().add(btn2);
40.
41.
JButton btn3 =
new
JButton(
"Button 3"
);
42.
btn3.setBounds(
53
,
137
,
89
,
23
);
43.
getContentPane().add(btn3);
44.
45.
JButton btn4 =
new
JButton(
"Button 4"
);
46.
btn4.setBounds(
254
,
94
,
89
,
23
);
47.
getContentPane().add(btn4);
48.
49.
50.
}
51.
}
Output
ตัวอย่าง Layout ของ AbsoluteLayout
แหล่งที่มา : thaicreate.com/java/java-gui-layout-absolutelayout