java - JOptionPane 输出文本副本

标签 java swing text output joptionpane

我没有使用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 的东西,您可以利用它的复制功能,而无需您做更多的工作...

enter image description here

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/

相关文章:

java - Java 中的事件序列

python - 当使用 f.read() 每个字母的迭代循环

Linux SED - 保留空间 - 所有行的一个值

java - 如何在没有 "400, ReasonPhrase: Bad Request."答案的情况下将工件版本重新部署到 Nexus?

java - 向 Pentaho Kettle 添加新的数据类型

java - 声明一个实现接口(interface)的对象,而无需显式使用特定的类

java - 如何使用 ExpectedException 规则在一个测试中测试多个异常?

java - 无法以编程方式添加到 JPanel

java - 添加新行后 JTable 不刷新

html - float 元素后的文本未正确填充