JFrame
- คอมโพเนนต์ที่เพิ่มเข้าไป จัดการโดย contentPane (ต้องใช้ contentPane.add())
- มี Title bar, Border, Menu bar (optional), Components
- สามารถ ย้าย, ปรับขนาด, minimize (iconify) ได้
- ไม่ใช่ subclass ของ JComponent
- ค่าเริ่มต้นแสดงมุมซ้ายบน ใช้ setLocation(x, y) ย้ายตำแหน่ง
ตัวอย่าง JFrame
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameDemo {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JLabel lbl = new JLabel("JFrame Demo");
lbl.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(lbl, BorderLayout.CENTER);
frame.setSize(375, 275);
frame.setVisible(true);
}
}
JDialog
- คล้าย JFrame แต่สามารถตั้งเป็น Modal ได้ (บล็อกหน้าต่างอื่น)
- Modal dialogs บล็อก input หน้าต่างอื่น, Modeless dialogs อนุญาต input หน้าต่างอื่น
- ไม่มีปุ่ม minimize/maximize มุมขวาบน
- เหมาะสำหรับ popup, confirmation, input dialogs
ตัวอย่าง JDialog
import javax.swing.JDialog;
import javax.swing.JLabel;
public class JDialogDemo extends JDialog {
public static void main(String[] args) {
try {
JDialogDemo dialog = new JDialogDemo();
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public JDialogDemo() {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("Welcome to Tutorials Point");
setBounds(100, 100, 359, 174);
getContentPane().setLayout(null);
JLabel label = new JLabel("Welcome to Tutorials Point");
label.setBounds(86, 37, 175, 29);
getContentPane().add(label);
}
}
ตารางเปรียบเทียบ
| คุณสมบัติ | JFrame | JDialog |
| Title bar | มี | มี |
| Minimize/Maximize | มี | ไม่มี |
| Modal | ไม่ได้ (เป็น top-level) | ตั้งได้ (Modal/Modeless) |
| Parent | ไม่มี (top-level) | มักมี parent frame |
| ใช้งาน | หน้าต่างหลักแอป | Dialog, Popup, Wizard |