Series Java Swing Bài 39: JFileChooser & JColorChooser - Hộp thoại chọn File và Bảng chọn màu
Trong bất kỳ phần mềm nào, thao tác Mở file (chọn ảnh đại diện, import dữ liệu) và Lưu file (xuất báo cáo Excel, lưu văn bản) là những tính năng cơ bản nhất. Tương tự, việc cho phép người dùng tùy chỉnh màu sắc giao diện cũng làm tăng trải nghiệm sử dụng (UX).
Thay vì phải tự tay vẽ ra một cửa sổ với hàng tá thư mục, ổ đĩa để người dùng chọn file, Java Swing cung cấp sẵn 2 "cỗ máy" đã được lập trình hoàn chỉnh, giao tiếp trực tiếp với hệ điều hành của bạn: JFileChooser và JColorChooser.
1. JFileChooser: Hộp thoại quản lý File
JFileChooser cung cấp một giao diện chuẩn xác với hệ điều hành bạn đang dùng (Windows, macOS, hoặc Linux) để duyệt file.
Hai chế độ cơ bản: Open và Save
-
showOpenDialog(parent): Hiển thị hộp thoại mang ý nghĩa "Mở file". Nút bấm sẽ hiện chữ "Open". -
showSaveDialog(parent): Hiển thị hộp thoại mang ý nghĩa "Lưu file". Nút bấm sẽ hiện chữ "Save".
Cả hai hàm này đều sẽ làm ứng dụng tạm dừng và chờ người dùng thao tác. Sau khi người dùng chọn xong, hàm sẽ trả về một số nguyên (int) để bạn biết họ đã làm gì:
-
JFileChooser.APPROVE_OPTION: Người dùng đã chọn file và bấm OK/Open/Save. -
JFileChooser.CANCEL_OPTION: Người dùng bấm Cancel hoặc dấu X để thoát.
Java
JFileChooser fileChooser = new JFileChooser();
// Mở hộp thoại chọn file
int response = fileChooser.showOpenDialog(this);
if (response == JFileChooser.APPROVE_OPTION) {
// Lấy đối tượng File mà người dùng vừa chọn
java.io.File file = fileChooser.getSelectedFile();
System.out.println("Đường dẫn file: " + file.getAbsolutePath());
}
Bộ lọc định dạng File (FileNameExtensionFilter)
Mặc định, JFileChooser hiển thị mọi loại file (All Files). Để phần mềm chuyên nghiệp hơn, bạn nên giới hạn chỉ cho phép chọn những file hợp lệ (Ví dụ: Chỉ chọn ảnh .jpg, .png).
Java
import javax.swing.filechooser.FileNameExtensionFilter;
JFileChooser chooser = new JFileChooser();
// Tạo bộ lọc cho file hình ảnh
FileNameExtensionFilter filter = new FileNameExtensionFilter("Hình ảnh (JPG, PNG, GIF)", "jpg", "png", "gif");
// Gắn bộ lọc vào JFileChooser
chooser.setFileFilter(filter);
2. JColorChooser: Bảng chọn màu chuyên nghiệp
Khác với JFileChooser cần phải khởi tạo đối tượng, JColorChooser cung cấp một hàm static cực kỳ tiện lợi để gọi bảng chọn màu lên bằng đúng 1 dòng code.
Hộp thoại này tích hợp sẵn các công cụ chọn màu cực mạnh (Bảng màu cơ bản, Vòng xoay màu HSV, Hệ màu RGB) giống hệt các phần mềm đồ họa chuyên nghiệp.
Java
// Cú pháp: JColorChooser.showDialog(parent, tiêu_đề, màu_mặc_định_khi_mở)
Color selectedColor = JColorChooser.showDialog(this, "Chọn màu chữ", Color.BLACK);
// Nếu người dùng bấm Cancel, hàm sẽ trả về null
if (selectedColor != null) {
textArea.setForeground(selectedColor); // Đổi màu chữ
}
3. Source Code Thực Chiến: Ứng Dụng Text Editor Mini
Đoạn mã dưới đây kết hợp cả JFileChooser và JColorChooser để tạo ra một phần mềm ghi chú. Bạn có thể tự do gõ văn bản, đổi màu chữ, đổi màu nền, lưu thành một file .txt vào máy tính, và mở file .txt đó lên lại.
(Lưu ý: Để code đọc/ghi file ngắn gọn và hiện đại nhất, bài học sử dụng thư viện java.nio.file.Files của Java 8+).
Java
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.nio.file.Files;
public class ChooserDemo extends JFrame {
private JTextArea textArea;
private JFileChooser fileChooser;
public ChooserDemo() {
setTitle("Notepad Pro - JFileChooser & JColorChooser (Bài 39)");
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
// ==========================================
// 1. KHỞI TẠO JFILECHOOSER (DÙNG CHUNG)
// ==========================================
fileChooser = new JFileChooser();
// Thiết lập bộ lọc chỉ cho phép chọn file .txt
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files (*.txt)", "txt");
fileChooser.setFileFilter(filter);
// ==========================================
// 2. THANH CÔNG CỤ (NÚT BẤM)
// ==========================================
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
topPanel.setBackground(new Color(236, 240, 241)); // Màu nền xám nhạt
JButton btnOpen = new JButton("Mở File");
JButton btnSave = new JButton("Lưu File");
JButton btnTextColor = new JButton("Đổi màu Chữ");
JButton btnBgColor = new JButton("Đổi màu Nền");
topPanel.add(btnOpen);
topPanel.add(btnSave);
topPanel.add(new JSeparator(SwingConstants.VERTICAL)); // Vạch kẻ phân cách
topPanel.add(btnTextColor);
topPanel.add(btnBgColor);
add(topPanel, BorderLayout.NORTH);
// ==========================================
// 3. KHU VỰC SOẠN THẢO (JTEXTAREA)
// ==========================================
textArea = new JTextArea("Hãy gõ gì đó vào đây...\nHoặc mở một file text từ máy tính của bạn.");
textArea.setFont(new Font("Consolas", Font.PLAIN, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setMargin(new Insets(10, 10, 10, 10)); // Căn lề padding
add(new JScrollPane(textArea), BorderLayout.CENTER);
// ==========================================
// 4. XỬ LÝ SỰ KIỆN: JFILECHOOSER
// ==========================================
// --- LOGIC MỞ FILE ---
btnOpen.addActionListener(e -> {
int response = fileChooser.showOpenDialog(this);
if (response == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try {
// Đọc toàn bộ nội dung file và nhét vào textArea
String content = new String(Files.readAllBytes(selectedFile.toPath()));
textArea.setText(content);
setTitle("Notepad Pro - " + selectedFile.getName());
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Lỗi đọc file: " + ex.getMessage(), "Lỗi", JOptionPane.ERROR_MESSAGE);
}
}
});
// --- LOGIC LƯU FILE ---
btnSave.addActionListener(e -> {
int response = fileChooser.showSaveDialog(this);
if (response == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
// Tự động thêm đuôi .txt nếu người dùng quên gõ
if (!fileToSave.getName().toLowerCase().endsWith(".txt")) {
fileToSave = new File(fileToSave.getAbsolutePath() + ".txt");
}
try {
// Ghi nội dung từ textArea xuống file
Files.write(fileToSave.toPath(), textArea.getText().getBytes());
JOptionPane.showMessageDialog(this, "Đã lưu thành công!", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
setTitle("Notepad Pro - " + fileToSave.getName());
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Lỗi ghi file: " + ex.getMessage(), "Lỗi", JOptionPane.ERROR_MESSAGE);
}
}
});
// ==========================================
// 5. XỬ LÝ SỰ KIỆN: JCOLORCHOOSER
// ==========================================
// --- ĐỔI MÀU CHỮ ---
btnTextColor.addActionListener(e -> {
// Hiển thị hộp thoại chọn màu, màu mặc định lúc mới mở là màu chữ hiện tại
Color newColor = JColorChooser.showDialog(this, "Chọn màu chữ", textArea.getForeground());
if (newColor != null) {
textArea.setForeground(newColor);
}
});
// --- ĐỔI MÀU NỀN ---
btnBgColor.addActionListener(e -> {
Color newColor = JColorChooser.showDialog(this, "Chọn màu nền", textArea.getBackground());
if (newColor != null) {
textArea.setBackground(newColor);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new ChooserDemo().setVisible(true));
}
}
Hãy copy chạy thử chương trình này. Bạn hãy thử gõ một đoạn văn, bấm "Đổi màu Nền" sang đen, "Đổi màu Chữ" sang xanh lá cây để tạo phong cách Hacker, sau đó bấm "Lưu File" ra ngoài màn hình Desktop. Bạn vừa hoàn thiện một ứng dụng thực tế có khả năng tương tác trực tiếp với máy tính của mình rồi đấy!
All rights reserved