из консольного вывода в JTextArea - PullRequest
0 голосов
/ 17 октября 2018

Я делаю Java-приложение Swing на Eclipse.

Когда нажимается кнопка, открывается рамка, и вывод консольной информации должен также отображаться на 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);
...