如何在 Java 中实现 JOptionPane 消息对话框的长文本?
JOptionPane 是 JComponent 类的子类,其中包括用来创建和定制**模态** **对话框** **框** 的静态方法。可以使用 **JOptionPane 类来代替 **JDialog 类来最小化代码的复杂性。JOptionPane 显示具有四个标准图标之一的对话框框(问号、信息、警告和错误),还可以显示用户指定的自定义图标。默认情况下,JOptionPane 消息对话框可以支持**单行文本,**我们还可以通过定制 JTextArea 类来实现一个带**长文本** 的 JOptionPane 消息对话框。
示例
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(); } }
输出
广告