从控制台输出到JTextArea

时间:2018-10-17 16:11:15

标签: java swing console jtextarea

我正在Eclipse上制作一个Swing Java应用程序。

单击按钮时,将打开一个框架,控制台输出也应显示在该框架的JTextArea上。

JButton btnNewButton_1 = new JButton("ConsoleOutput");
btnNewButton_1.addActionListener(new ActionListener() {             
    public void actionPerformed(ActionEvent e) {

        JFrame aFrame = new JFrame();

        JTextArea jta = new JTextArea(10, 10);

        System.out.println("after jta");

        OutputConsole out = new OutputConsole();

        out.redirectSystemStreams() ;

        aFrame.getContentPane().add(jta);

        aFrame.pack();
        aFrame.show();

        System.out.println("Test 1");

我的OutputConsole类是:

public class OutputConsole {
    JTextArea jtx;
    private void updateTextArea(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                jtx .append(text);
            }
        });
    }
    @SuppressWarnings("unused")
    public void redirectSystemStreams() {
        OutputStream out = new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                updateTextArea(String.valueOf((char) b));
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                updateTextArea(new String(b, off, len));
            }

            @Override
            public void write(byte[] b) throws IOException {
                write(b, 0, b.length);
            }
        };

        System.setOut(new PrintStream(out, true));
        System.setErr(new PrintStream(out, true));
    }

}

现在框架打开了,但在JTextArea上看不到任何东西。

请提出建议。

单击此按钮时,命令控制台输出应显示在JTexArea上。

JButton btnNewButton = new JButton("SR# Number");
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 11));
btnNewButton.addActionListener(new ActionListener() {
    @SuppressWarnings("null")
    public void actionPerformed(ActionEvent arg0) {
        String command = " cmd.exe /c  ver"; 
        try {
            Process p = Runtime.getRuntime().exec(command);

            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = reader.readLine();

            while (line != null) {
                System.out.println("ms#  " + line + "\n \r" + line);

                //JOptionPane.showMessageDialog(null, "ms version is " + line + "\n \r" + line);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
});
    btnNewButton.setBounds(127, 108, 88, 23);
    frame.getContentPane().add(btnNewButton);

0 个答案:

没有答案