2010-10-30 16 views
28

En un artículo cada la respuesta a la pregunta "¿Cómo agregar una cadena a un JEditorPane?" es algo así comoJTextPane que agrega una nueva cadena

jep.setText(jep.getText + "new string"); 

he intentado esto:

jep.setText("<b>Termination time : </b>" + 
         CriterionFunction.estimateIndividual_top(individual) + " </br>"); 
jep.setText(jep.getText() + "Processes' distribution: </br>"); 

Y como resultado que obtuve "tiempo de terminación: 1000" sin "distribución de Procesos:"

Por qué ocurrió esto? ??

Respuesta

56

que duda de que es el método recomendado para anexar texto. Esto significa que cada vez que cambie un texto necesita volver a rastrear todo el documento. La razón por la que las personas pueden hacer esto es porque no entienden cómo usar un JEditorPane. Eso me incluye a mí.

Prefiero usar un JTextPane y luego usar los atributos. Un ejemplo sencillo podría ser algo como:

JTextPane textPane = new JTextPane(); 
textPane.setText("original text"); 
StyledDocument doc = textPane.getStyledDocument(); 

// Define a keyword attribute 

SimpleAttributeSet keyWord = new SimpleAttributeSet(); 
StyleConstants.setForeground(keyWord, Color.RED); 
StyleConstants.setBackground(keyWord, Color.YELLOW); 
StyleConstants.setBold(keyWord, true); 

// Add some text 

try 
{ 
    doc.insertString(0, "Start of text\n", null); 
    doc.insertString(doc.getLength(), "\nEnd of text", keyWord); 
} 
catch(Exception e) { System.out.println(e); } 
+0

Gracias, intentaré esto. – Dmitry

+0

¡Eso funciona! Pero ¿por qué setText + get Text no funciona? – Dmitry

+3

Eso recrearía el Documento y perdería todos los atributos personalizados que agregó anteriormente. – camickr

4

setText es establecer todo el texto en un panel de texto. Use la interfaz StyledDocument para agregar, eliminar y modificar el texto.

txtPane.getStyledDocument().insertString(
    offsetWhereYouWant, "text you want", attributesYouHope); 
+0

¡Gracias, Istao! – Dmitry

23

Un JEditorPane, sólo como un JTextPane tiene un Document que se puede utilizar para insertar cadenas.

Lo que usted querrá hacer para añadir texto en un JEditorPane es este fragmento:

JEditorPane pane = new JEditorPane(); 
/* ... Other stuff ... */ 
public void append(String s) { 
    try { 
     Document doc = pane.getDocument(); 
     doc.insertString(doc.getLength(), s, null); 
    } catch(BadLocationException exc) { 
     exc.printStackTrace(); 
    } 
} 

Probé esto y funcionó bien para mí. El doc.getLength() es donde desea insertar la cadena, obviamente con esta línea la agregará al final del texto.

+1

¡Gracias, eso funciona! – Dmitry

+0

Pero ¿por qué setText + get Text no funciona? – Dmitry

+0

No puedo responder con seguridad, no he jugado nada con JEditorPane, solo JTextPane en su mayoría. Tendría que jugar e investigar antes de poder responder eso. –

Cuestiones relacionadas