Java Swing – Hộp Thoại

Rate this post

Trong phần này chúng ta sẽ tìm hiểu cách sử dụng một số hộp thoại cơ bản là MessageBox, JFileChooser, JColorChooser.

Hộp thoại (Dialog) có 2 loại là modal (trạng thái) và modeless (vô trạng thái), hộp thoại modal khi hiện ra sẽ không cho phép người dùng tương tác với cửa sổ cha của nó, còn hộp thoại modeless thì cho phép.

Message Dialog

MessageBox dùng để hiển thị thông báo cho người dùng.

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MessageDialogsEx extends JFrame {
    
    private JPanel panel;

    public MessageDialogsEx() {

        initUI();
    }

    private void initUI() {
        
        panel = (JPanel) getContentPane();
 
        JMenuBar menubar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
 
        JMenuItem about = new JMenuItem("About");
        about.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                JOptionPane.showMessageDialog(
                    panel, 
                    "This is a modal MessageBox", 
                    "About", 
                    JOptionPane.INFORMATION_MESSAGE);
            }
        });
         
        fileMenu.add(about);
      
        menubar.add(fileMenu);
        setJMenuBar(menubar);
 
        setTitle("Dialog Example");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                MessageDialogsEx md = new MessageDialogsEx();
                md.setVisible(true);
            }
        });
    }
}

Chúng ta tạo một menu có item là About, click vào item này thì hiển thị một messagebox.

JOptionPane.showMessageDialog(panel, "This is a modal MessageBox", "About", 
                              JOptionPane.INFORMATION_MESSAGE);

Để hiển thị MessageBox thì chúng ta gọi phương thức JOptionPane.showMessageBox(), JOptionPane là một lớp tĩnh nên bạn có thể gọi nó bất kỳ lúc nào mà không cần phải tạo một đối tượng mới. Tham số gồm có đối tượng cửa sổ cha hoặc panel cha, text, title, và kiểu hộp thoại. Kiểu hộp thoại có 4 kiểu sau đây:

  • ERROR_MESSAGE
  • WARNING_MESSAGE
  • QUESTION_MESSAGE
  • INFORMATION_MESSAGE

Capture

Confirm Dialog

Đây là kiểu hộp thoại cho bạn 2 lựa chọn để trả lời cho một câu hỏi nào đó.

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
class ConfirmDialogEx extends JFrame{

    private JPanel panel;
    public ConfirmDialogEx() {        
        initUI();
    }

    private void initUI() {

        panel = (JPanel) getContentPane();
 
        JMenuBar menubar = new JMenuBar();
        JMenu fileMenu = new JMenu("File"); 
 
        JMenuItem exit = new JMenuItem("Exit");
        exit.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                int n = JOptionPane.showConfirmDialog(
                            panel, 
                            "Are you sure you want to quit?", 
                            "Alert", 
                            JOptionPane.YES_NO_OPTION);
                if(n == JOptionPane.YES_OPTION)
                    System.exit(0);
            }
        });
 
        fileMenu.add(exit);
 
        menubar.add(fileMenu);
        setJMenuBar(menubar);
  
        setTitle("Dialog Example");
        setSize(400, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }   

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JDialogEx sd = new JDialogEx();
                sd.setVisible(true);
            }
        });
    }
}

Chúng ta tạo một menu có một item là exit, click vào item này thì hộp thoại sẽ hiện ra để xác nhận.

int n = JOptionPane.showConfirmDialog(
            panel, 
            "Are you sure you want to quit?", 
            "Alert", 
            JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION)
    System.exit(0);

Chúng ta dùng phương thức showConfirmDialog() với kiểu hộp thoại là JOptionPane.YES_NO_QUESTION. Phương thức này sẽ trả về một giá trị int khi người dùng click vào một trong hai nút Yes hoặc No tương ứng.

Capture

JFileChooser

JFileChooser là hộp thoại cho phép bạn chọn file.

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileChooserEx extends JFrame {

    private JPanel panel;
    private JLabel path;

    public FileChooserEx() {

        initUI();
    }

    private void initUI() {

        panel = new JPanel();
        panel.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
 
        JButton openFileButton = new JButton("Open File"); 
        openFileButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                JFileChooser fc = new JFileChooser();
                fc.addChoosableFileFilter(new FileNameExtensionFilter(
                    "Image (jpg, jpeg, png, bmp, gif)", 
                    "jpg", "jpeg", "png", "bmp", "gif"
                ));
                int n = fc.showOpenDialog(panel);
 
                if(n == JFileChooser.APPROVE_OPTION)
                    path.setText(fc.getSelectedFile().getAbsolutePath());
            }
        });
 
        JButton openFolderButton = new JButton("Open Folder"); 
        openFolderButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                JFileChooser fc = new JFileChooser();
 
                int n = fc.showOpenDialog(panel);
                fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                if(n == JFileChooser.APPROVE_OPTION)
                    path.setText(fc.getSelectedFile().getAbsolutePath());
            }
        });
 
        panel.add(Box.createRigidArea(new Dimension(5, 5)));
        panel.add(openFileButton);
        panel.add(Box.createRigidArea(new Dimension(5, 0)));
        panel.add(openFolderButton);
 
        add(panel);
 
        path = new JLabel("Path:"); 
        path.setPreferredSize(new Dimension(-1, 22));
        path.setBorder(LineBorder.createGrayLineBorder());            
        add(path, BorderLayout.SOUTH);
 
        setTitle("Dialog Example");
        setSize(300, 100);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
   
    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FileChooserEx fcd = new FileChooserEx();
                fcd.setVisible(true);
            }
        });
    }
}

Chúng ta tạo 2 button và một label, một button mở hộp thoại chọn file, một button mở hộp thoại chọn thư mục, đường dẫn đến file và thư mục được chọn sẽ hiển thị trên label.

JFileChooser fc = new JFileChooser();

Khác với 2 messagebox trên, ở đây bạn phải tạo một đối tượng JFileChooser riêng.

fc.addChoosableFileFilter(new FileNameExtensionFilter(
    "Image (jpg, jpeg, png, bmp, gif)", 
    "jpg", "jpeg", "png", "bmp", "gif"
));

Bạn có thể thêm các bộ lọc file theo phần mở rộng của tên file với phương thức addChoosableFileFilter()  và tham số là một đối tượng FileNameExtensionFilter.

int n = fc.showOpenDialog(panel);

Để hiển thị hộp thoại chọn file thì chúng ta gọi phương thức showOpenDialog().

if(n == JFileChooser.APPROVE_OPTION)
    path.setText(fc.getSelectedFile().getAbsolutePath());

Nếu có file được chọn thì phương thức này sẽ trả về một giá trị int và bạn có thể lấy đường dẫn đến file được chọn đó.

fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

Ngoài ra bạn cũng có thể chỉ định là chỉ mở thư mục với phương thức setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY).

Untitled

JColorChooser

Java Swing cung cấp lớp JColorChooser tạo hộp thoại chọn màu rất mạnh.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

public class ColorChooserEx extends JFrame {

    private JPanel panel; 
    private JPanel display;

    public ColorChooserEx() {

        initUI();
    }

    private void initUI() {

        panel = new JPanel();
 
        JButton openColor = new JButton("Choose Color");
        openColor.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                Color color = JColorChooser.showDialog(
                    panel, 
                    "Choose color", 
                    Color.white);
                display.setBackground(color);
            }
        });
 
        display = new JPanel();
        display.setPreferredSize(new Dimension(150, 150));
        display.setBorder(LineBorder.createGrayLineBorder());
        display.setBackground(Color.black); 
 
        panel.add(openColor);
        panel.add(display);
        add(panel);
  
        pack();
 
        setTitle("Dialog Example"); 
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                ColorChooserEx ccd = new ColorChooserEx();
                ccd.setVisible(true);
            }
        });
    }
}

Để mở hộp thoại chọn màu thì chỉ cần gọi JColorChooser.showDialog(), tham số đầu tiên là đối tượng cửa sổ cha hoặc panel cha, tham số thứ 2 là tiêu đề của hộp thoại, tham số thứ 3 là màu mặc định khi mở.

Color color = JColorChooser.showDialog(panel, "Choose color", Color.white);
display.setBackground(color);

Phương thức này sẽ trả về một đối tượng Color chứa thông tin màu đã được chọn hoặc null nếu người dùng không chọn màu nào.

Capture

0 0 votes
Article Rating
Subscribe
Thông báo cho tôi qua email khi
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Inline Feedbacks
View all comments
Hoàng Thống
6 năm trước

Chào, bào viết bạn rất hữu ích, very useful, và cho t hỏi t muốn sau khi chọn file bằng jfilechoser xong thì có thể sử dụng file nó, như 1 picture làm icon cho một componemt nào đó chẳng hạn?