Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách triển khai hộp thoại JOptionPane với văn bản dài trong Java

JOptionPane là lớp con của JComponent bao gồm phương thức static tạo và tùy chỉnh hộp thoại modal (modal dialog). JOptionPane dùng thay cho JDialog để giảm độ phức tạp code. JOptionPane hiển thị hộp thoại với 4 icon tiêu chuẩn (question, information, warning, error) hoặc icon tùy chỉnh. Mặc định JOptionPane chỉ hỗ trợ văn bản một dòng, chúng ta có thể triển khai JOptionPane với văn bản dài bằng cách tùy chỉnh JTextArea.

Ví dụ

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JOptionPaneScrollTextMessage extends JFrame {
    private JButton btn;
    String msg;

    public JOptionPaneScrollTextMessage() {
        setTitle("JOptionPaneScrollTextMessage Test");
        msg = "Java là ngôn ngữ lập trình tạo phần mềm cho nhiều nền tảng.\nKhi lập trình viên viết ứng dụng Java, mã bytecode\n" +
              "chạy trên hầu hết HĐH (OS), bao gồm Windows, Linux, Mac OS. Java lấy nhiều cú pháp\n" +
              "từ C và C++.\nJava phát triển giữa những năm 1990 bởi James A. Gosling, cựu khoa học máy tính Sun Microsystems.";
        btn = new JButton("Show Dialog");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JTextArea jta = new JTextArea(5, 15);
                jta.setText(msg);
                jta.setEditable(false);
                JScrollPane jsp = new JScrollPane(jta);
                JOptionPane.showMessageDialog(null, jsp);
            }
        });
        add(btn, BorderLayout.NORTH);
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new JOptionPaneScrollTextMessage();
    }
}

Kết quả

Cách triển khai hộp thoại JOptionPane với văn bản dài trong Java