2013-02-21 1 views
0

나는 간단한 Java Swing 콘솔을 수정했으며 키워드에 강조 표시 양식을 추가하기로했습니다 (플래그가 지정된 줄 옆에 색칠하여). 키워드 "Exception"을 검색하여 오류가 발생하면 제대로 작동하지만, 키워드가있는 System.out.println을 실행하면 모든 것이 강조 표시됩니다. 문자열이 어떻게 든이 문자열에 이미 입력 된 문자열과 결합되어 있다고 생각합니다.이 오류는이 오류의 원인이지만 해결하는 데 문제가 있습니다.Java에서 키워드 강조 표시 문제 (System.out 사용)

enter image description here

텍스트에 "Hello World 2"및 "는이 콘솔에 오류가 발생하자"강조해서는 안 :

여기 스크린 샷입니다. , enter image description here

이를 복제하려면 독자 (1)에 System.out.prinln 문을 추가로 입력을 추가 : 나는 약간의 테스트를하고있다

// Edited by Jeff B 
// A simple Java Console for your application (Swing version) 
// Requires Java 1.1.5 or higher 
// 
// Disclaimer the use of this source is at your own risk. 
// 
// Permision to use and distribute into your own applications 
// 
// RJHM van den Bergh , [email protected] 

import java.io.*; 
import java.util.ArrayList; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

class textAreaC extends JTextArea { 
    int rowCount; 
    int rowHeight; 
    ArrayList<Point> exPoint = new ArrayList<Point>(); 

    public textAreaC() { 
     rowHeight = this.getRowHeight(); 
    } 

    public void paint(Graphics g) { 
     super.paint(g); 
     g.setColor(Color.red); 
     for (int i = 0; i < exPoint.size(); i++) { 
      g.fillRect(3, exPoint.get(i).x * rowHeight, 10, exPoint.get(i).y 
        * rowHeight); 
     } 
    } 

    public void append(String str) { 
     int rows = str.split("\r\n|\r|\n").length; 
     if (str.contains("Exception")) { 
      //System.out.println("This was the string: " + str + "It has " + rows + "rows" + " End String"); 
      exPoint.add(new Point(rowCount, rows)); 
     } 
     rowCount += rows; 
     super.append(str); 

    } 
} 

public class Console extends WindowAdapter implements WindowListener, 
     ActionListener, Runnable { 
    private JFrame frame; 
    private textAreaC textArea; 
    private Thread reader; 
    private Thread reader2; 
    private boolean quit; 

    private final PipedInputStream pin = new PipedInputStream(); 
    private final PipedInputStream pin2 = new PipedInputStream(); 

    Thread errorThrower; // just for testing (Throws an Exception at this Console 

    public Console() { 
     // create all components and add them 
     frame = new JFrame("Java Console"); 
     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
     Dimension frameSize = new Dimension((int) (screenSize.width/2), 
       (int) (screenSize.height/2)); 
     int x = (int) (frameSize.width/2); 
     int y = (int) (frameSize.height/2); 
     frame.setBounds(x, y, frameSize.width, frameSize.height); 

     textArea = new textAreaC(); 
     textArea.setEditable(false); 
     textArea.setMargin(new Insets(3, 20, 3, 3)); 
     JButton button = new JButton("clear"); 
     frame.getContentPane().setLayout(new BorderLayout()); 
     frame.getContentPane().add(new JScrollPane(textArea), 
       BorderLayout.CENTER); 
     frame.getContentPane().add(button, BorderLayout.SOUTH); 
     frame.setVisible(true); 
     frame.addWindowListener(this); 
     button.addActionListener(this); 

     try { 
      PipedOutputStream pout = new PipedOutputStream(this.pin); 
      System.setOut(new PrintStream(pout, true)); 
     } catch (java.io.IOException io) { 
      textArea.append("Couldn't redirect STDOUT to this console\n" 
        + io.getMessage()); 
     } catch (SecurityException se) { 
      textArea.append("Couldn't redirect STDOUT to this console\n" 
        + se.getMessage()); 
     } 

     try { 
      PipedOutputStream pout2 = new PipedOutputStream(this.pin2); 
      System.setErr(new PrintStream(pout2, true)); 
     } catch (java.io.IOException io) { 
      textArea.append("Couldn't redirect STDERR to this console\n" 
        + io.getMessage()); 
     } catch (SecurityException se) { 
      textArea.append("Couldn't redirect STDERR to this console\n" 
        + se.getMessage()); 
     } 

     quit = false; // signals the Threads that they should exit 

     // Starting two seperate threads to read from the PipedInputStreams    
     // 
     reader = new Thread(this); 
     reader.setDaemon(true); 
     reader.start(); 
     // 
     reader2 = new Thread(this); 
     reader2.setDaemon(true); 
     reader2.start(); 

     // testing part 
     // you may omit this part for your application 
     // 
     //System.out.println("Test me please Exception\n testing 123"); 
     System.out.flush(); 
     System.out.println("Hello World 2"); 

     System.out.println("\nLets throw an error on this console"); 
     errorThrower = new Thread(this); 
     errorThrower.setDaemon(true); 
     errorThrower.start(); 
    } 

    public synchronized void windowClosed(WindowEvent evt) { 
     quit = true; 
     this.notifyAll(); // stop all threads 
     try { 
      reader.join(1000); 
      pin.close(); 
     } catch (Exception e) { 
     } 
     try { 
      reader2.join(1000); 
      pin2.close(); 
     } catch (Exception e) { 
     } 
     System.exit(0); 
    } 

    public synchronized void windowClosing(WindowEvent evt) { 
     frame.setVisible(false); // default behaviour of JFrame 
     frame.dispose(); 
    } 

    public synchronized void actionPerformed(ActionEvent evt) { 
     textArea.setText(""); 
    } 

    public synchronized void run() { 
     try { 
      while (Thread.currentThread() == reader) { 
       try { 
        this.wait(100); 
       } catch (InterruptedException ie) { 
       } 
       if (pin.available() != 0) { 
        String input = this.readLine(pin); 
        textArea.append(input); 
        //System.out.println(input.split("\r\n|\r|\n").length); 
       } 
       if (quit) 
        return; 
      } 

      while (Thread.currentThread() == reader2) { 
       try { 
        this.wait(100); 
       } catch (InterruptedException ie) { 
       } 
       if (pin2.available() != 0) { 
        String input = this.readLine(pin2); 
        textArea.append(input); 
       } 
       if (quit) 
        return; 
      } 
     } catch (Exception e) { 
      textArea.append("\nConsole reports an Internal error."); 
      textArea.append("The error is: " + e); 
     } 

     // just for testing (Throw a Nullpointer after 1 second) 
     if (Thread.currentThread() == errorThrower) { 
      try { 
       this.wait(1000); 
      } catch (InterruptedException ie) { 
      } 
      throw new NullPointerException(
        "Application test: throwing an NullPointerException It should arrive at the console"); 
     } 
    } 

    public synchronized String readLine(PipedInputStream in) throws IOException { 
     String input = ""; 
     do { 
      int available = in.available(); 
      if (available == 0) 
       break; 
      byte b[] = new byte[available]; 
      in.read(b); 
      input = input + new String(b, 0, b.length); 
     } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit); 
     return input; 
    } 

    public static void main(String[] arg) { 
     new Console(); // create console with not reference 
    } 
} 

이 출력에서보세요 문자열의 끝.

if (pin.available()!=0) 
    { 

     String input=this.readLine(pin); 
     System.out.println("this was printed by the thread second " + input); 
     textArea.append(input); 
     //System.out.println(input.split("\r\n|\r|\n").length); 
    } 
if (quit) return; 

그것은 하나의 입력으로 그 prinlns을 모두 취급하고,이 뭔가 자바가하고있는, 또는 :

System.out.println("There should be a string before me."); 
System.out.flush(); 
System.out.println("Test me please Exception"); 
System.out.flush(); 
System.out.println("Test print 2"); 
System.out.flush(); 
System.out.println("Test print 3"); 
System.out.flush(); 
System.out.println("Test me please Exception 2"); 
System.out.flush(); 
System.out.println("Exception here lololol"); 
System.out.flush(); 
System.out.println("Hello World 2"); 
System.out.flush(); 

그리고 내 판독기는 다음과 같다 : 이것은 내 prinlns 모양을하다 내가 뭔가 빠진거야?

+0

바람직하지 않은 동작을 보여주는 스크린 샷을 추가해야합니다. 대부분의 사람들은 단어로 설명하는 것을보기 위해 코드를 실행하려고하지 않을 것입니다. – Perception

+0

감사합니다, –

+0

문제는 얼마나 자주 append() 메서드가 호출되는지입니다. 여러 System.out.println() 호출을 결합하여 append() 메소드를 한 번 호출합니다. 이것은 모든 호출 후에 flush()를 추가 할 때조차도 발생합니다. 각 println() 호출을 append() 호출과 동일하게하는 방법을 확신하지 못합니다. – camickr

답변

1

HTML을 출력용으로 사용하면 더 쉽습니다. 첫 번째 텍스트 <html>처럼 (아주 느슨한 HTML). 또는 콘텐츠 형식을 설정하십시오. <br> 등 줄을 추가하십시오.

더 유연합니다.


두 줄의 여러 줄을 추가했습니다. 행 수가 많으면 문자열의 모든 행이 빨간색이됩니다. 어쩌면이 차선책 버전은 당신이 의도 한 것과 더 비슷할 수도 있습니다.

@Override 
public void append(String str) { 
    String[] lines = str.split("\r\n|\r|\n"); 
    int rows = lines.length; 
    for (String line : lines) { 
     super.append(line + "\n"); 
     if (line.contains("Exception")) { 
      exPoint.add(new Point(rowCount, 1)); // 1 line 
     } 
     ++rowCount; 
    } 
} 
+0

JTextArea가 아닌 JEditorPane을 사용해야한다고 생각하십니까?(전에는 JEditorPane을 사용하고 있었지만 여러 스레드에서 사용하면 문제가 발생했습니다.) –

+0

맞습니다 : JEditorPane 또는 JTextPane. 다중 스레드에주의해야합니다. 그래도 할 수 있어야합니다. –

+0

요구 사항은 텍스트를 강조 표시하지 않고 왼쪽 아래로 막대를 칠하는 것입니다. 동적 HTML 작업은이 경우 일반 텍스트로 작업하는 것보다 쉽지 않습니다. – camickr