我没有使用JOptionpane
的经验,但我需要一个简单的程序来简化我的生活。
我需要帮助的代码如下:
public static void main (String[] args) {
String input = "";
input = JOptionPane.showInputDialog("Enter code");
JOptionPane.showMessageDialog(null, toStringU(toArray(input)), "RESULT",
JOptionPane.INFORMATION_MESSAGE);
}
toStringU
方法给我一个很长的文本
我想在没有任何编译器的情况下运行它(一个独立的应用程序,双击,输入信息并获取结果)。
而且我无法从输出面板复制结果,我需要复制它。所以要么我需要复制它和/或我想将它写入一个 txt 文件(第二个文件会很棒)。
最佳答案
JOptionPane
允许您指定一个 Object
作为消息参数,如果此值是某种 Component
,它将被添加到 JOptionPane
(String
自动使用 JLabel
呈现)
通过设置不可编辑的类似 JTextArea
的东西,您可以利用它的复制功能,而无需您做更多的工作...
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) {
}
}
这也允许你写一个文件...
关于java - JOptionPane 输出文本副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16409387/