JOptionPane
允许你指定一个Object
作为消息参数,如果这个值是Component
某种类型的,它将被添加到JOptionPane
(String
s被自动渲染使用JLabel
)
通过设置像 aJTextArea
这样不可编辑的东西,您可以利用它的复制功能,而无需您做更多的工作......

import java.awt.EventQueue;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestOptionPane11 {
public static void main(String[] args) {
new TestOptionPane11();
}
public TestOptionPane11() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextArea ta = new JTextArea(10, 10);
ta.setText("This is some really long text that is likely to run over "
+ "the viewable area and require some additional space to render "
+ "properly, but you should be able to select and copy parts or "
+ "whole sections of the text as you, but it should remain "
+ "no editable...");
ta.setWrapStyleWord(true);
ta.setLineWrap(true);
ta.setCaretPosition(0);
ta.setEditable(false);
JOptionPane.showMessageDialog(null, new JScrollPane(ta), "RESULT", JOptionPane.INFORMATION_MESSAGE);
}
});
}
}
额外的副作用
另一个副作用是它实际上JTextArea
可以为你写它的内容Writer
......
FileWriter writer = null;
try {
writer = new FileWriter("SomeoutputFile.txt", false);
ta.write(writer);
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
}
它还允许您编写文件...