A JOptionPane เป็นคลาสย่อยของ JComponent คลาสซึ่งรวมถึง เมธอดแบบคงที่ สำหรับการสร้างและปรับแต่ง โมดอล กล่องโต้ตอบ กล่อง . JOptionPane สามารถใช้คลาสแทน JDialog คลาส เพื่อลดความซับซ้อนของรหัส JOptionPane จะแสดงไดอะล็อกบ็อกซ์ที่มีหนึ่งในสี่ไอคอนมาตรฐาน (คำถาม ข้อมูล คำเตือน และ ข้อผิดพลาด ) หรือไอคอนที่กำหนดเองซึ่งระบุโดยผู้ใช้ โดยค่าเริ่มต้น กล่องโต้ตอบข้อความ JOptionPane สามารถสนับสนุน ข้อความบรรทัดเดียว นอกจากนี้เรายังสามารถใช้กล่องโต้ตอบข้อความ JOptionPane กับ long tex t โดยกำหนด 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();
}
} ผลลัพธ์
