2013-09-30 17 views
5

Sto tentando di eseguire l'evidenziazione del testo in JTextPane. Sto usando SwingWorker per fare l'evidenziazione in background. Ma non sono in grado di ottenere l'output desiderato.
My Code è la seguente:
Main Class:Sintassi-Evidenziazione in JTextPane utilizzando SwingWorker

class MultiColor { 
    private static void displayGUI() { 
     final JTextPane ta = new JTextPane(); 
     JFrame frame = new JFrame("EXAMPLE"); 
     JButton jb = new JButton("Change"); 
     JScrollPane jsp = new JScrollPane(ta); 
     frame.add(jsp, BorderLayout.CENTER); 
     frame.add(jb, BorderLayout.PAGE_END); 
     frame.pack(); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.setVisible(true); 
     jb.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent ae) { 
       Modify mm = new Modify(ta); 
       mm.execute(); 
      } 
     }); 
    } 
    public static void main(String[] a) { 
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       displayGUI(); 
      } 
     }; 
     SwingUtilities.invokeLater(r); 
    } 
} 

e classe Modifica è:

class Modify extends SwingWorker<Void,Object> { 
    private JTextPane ta; 
    private StyleContext style; 
    private AttributeSet textStyle; 
    public Modify(JTextPane text) { 
     ta = text; 
    } 
    private void matching(String str){ 
     style = StyleContext.getDefaultStyleContext(); 
     textStyle = style.addAttribute(style.getEmptySet(),StyleConstants.Foreground, Color.red); 
     textStyle = style.addAttribute(textStyle,StyleConstants.FontSize, 15); 

     String regx = "\\b(class|int|void|static|final|public|private|protected|float|if|else|for|while|try|catch|boolean|import|return)\\b"; 
     String input = str; 
     Pattern p = Pattern.compile(regx); 
     Matcher m = p.matcher(input); 
     while(m.find()) 
      ta.getStyledDocument().setCharacterAttributes(m.start(),(m.end() - m.start()),textStyle, false); 
    } 
    @Override 
    protected Void doInBackground() { 
     matching(ta.getText()); 
     return null; 
    } 
    @Override 
    protected void done() { 
    } 
} 

E la mia uscita è:

enter image description here

voglio mostrare tutte le parole chiave con lo stile di testo specificato.
Come ottengo l'output desiderato.

+1

doInBackground è thread di lavoro, non designato per modificare qualcosa nella GUI Swing, è necessario utilizzare publish() o setProcess – mKorbel

risposta

4

Sembra che l'offset di evidenziazione sia disattivato.

Vedere Text and New Lines per la causa probabile e una soluzione semplice.