Вывод консоли веб-очистки в Swing GUI [дубликат]

, если вы хотите что-то более похожее на набор изменений ... можете использовать Counter

from collections import Counter

def diff(a, b):
  """ more verbose than needs to be, for clarity """
  ca, cb = Counter(a), Counter(b)
  to_add = cb - ca
  to_remove = ca - cb
  changes = Counter(to_add)
  changes.subtract(to_remove)
  return changes

lista = ['one', 'three', 'four', 'four', 'one']
listb = ['one', 'two', 'three']

In [127]: diff(lista, listb)
Out[127]: Counter({'two': 1, 'one': -1, 'four': -2})
# in order to go from lista to list b, you need to add a "two", remove a "one", and remove two "four"s

In [128]: diff(listb, lista)
Out[128]: Counter({'four': 2, 'one': 1, 'two': -1})
# in order to go from listb to lista, you must add two "four"s, add a "one", and remove a "two"
4
задан nicki 7 November 2013 в 16:48
поделиться

1 ответ

Если вы выполните поиск в Google: «stdout JTextArea», у вас будет несколько ссылок для решения вашей проблемы.

В последней ссылке buddybob расширяет java.io.OutputStream для печати стандартного вывода на его JTextArea. Я добавил его решение ниже.

TextAreaOutputStream.java

/*
*
* @(#) TextAreaOutputStream.java
*
*/

import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;

/**
* An output stream that writes its output to a javax.swing.JTextArea
* control.
*
* @author  Ranganath Kini
* @see      javax.swing.JTextArea
*/
public class TextAreaOutputStream extends OutputStream {
    private JTextArea textControl;

    /**
     * Creates a new instance of TextAreaOutputStream which writes
     * to the specified instance of javax.swing.JTextArea control.
     *
     * @param control   A reference to the javax.swing.JTextArea
     *                  control to which the output must be redirected
     *                  to.
     */
    public TextAreaOutputStream( JTextArea control ) {
        textControl = control;
    }

    /**
     * Writes the specified byte as a character to the
     * javax.swing.JTextArea.
     *
     * @param   b   The byte to be written as character to the
     *              JTextArea.
     */
    public void write( int b ) throws IOException {
        // append the data as characters to the JTextArea control
        textControl.append( String.valueOf( ( char )b ) );
    }  
}

TextAreaOutputStream расширяет класс java.io.OutputStream и переопределяет его перегрузку метода write(int), этот класс использует ссылку на экземпляр управления javax.swing.JTextArea, а затем добавляет к нему вывод всякий раз, когда вызывается метод write (int b).

Чтобы использовать класс TextAreaOutputStream, [yo] u должен использовать:

Использование

// Create an instance of javax.swing.JTextArea control
JTextArea txtConsole = new JTextArea();

// Now create a new TextAreaOutputStream to write to our JTextArea control and wrap a
// PrintStream around it to support the println/printf methods.
PrintStream out = new PrintStream( new TextAreaOutputStream( txtConsole ) );

// redirect standard output stream to the TextAreaOutputStream
System.setOut( out );

// redirect standard error stream to the TextAreaOutputStream
System.setErr( out );

// now test the mechanism
System.out.println( "Hello World" );
7
ответ дан Community 23 August 2018 в 00:28
поделиться
  • 1
    Привет, спасибо за ответ. Описанный выше код означает, что я должен создать другой .java-файл TextAreaOutputStream. а затем добавить код использования в основной метод моего класса AddNumber? Потому что я не вижу никаких изменений, происходящих с этим ... или я не понимаю его хорошо? – nicki 7 November 2013 в 13:33
  • 2
    Ну, как показывает использование, вам необходимо передать ссылку на ваш JTextArea и установить выход системы в ваш класс AddNumber, чтобы ваши системные вызовы отправлялись на JTextArea. – Mr. Polywhirl 7 November 2013 в 13:38
  • 3
    Я все еще не могу заставить его работать :( Извините за то, что вы раздражаете, но пытались сделать это уже довольно давно, без каких-либо успехов. – nicki 7 November 2013 в 14:09
  • 4
    это не работает для меня .... При применении кода ни моя консоль, ни моя TextArea не отображает любой sysout ... – Spade Johnsson 29 May 2015 в 11:30
Другие вопросы по тегам:

Похожие вопросы: