JOptionPane เป็น subclass ของ JComponent รวม static methods สำหรับสร้างและปรับแต่ง modal dialog boxes JOptionPane ใช้แทน JDialog เพื่อลดความซับซ้อนของโค้ด JOptionPane แสดง dialog boxes ด้วย standard icons 4 แบบ (question, information, warning และ error) หรือ custom icons ที่ user ระบุ โดย default JOptionPane message dialogs รองรับ single-line text เราสามารถ implement JOptionPane message dialog ด้วย long text ได้โดยปรับแต่งคลาส JTextArea
ตัวอย่าง
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 is a programming language that produces software for multiple platforms.\n When a "
+ "programmer writes a Java application, the compiled code\n"
+ "(known as bytecode) runs on most operating systems (OS), including \n Windows, Linux and Mac OS. Java derives much of its syntax \n"
+ "from the C and C++" + "programming languages.\n Java was developed in the mid-1990s by James "
+ "A. Gosling, a former computer scientist with 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();
}
}
Output
