From a taken example of this link, made an example where it is possible to change the text at runtime, using the classes StyleContext
and AttributeSet
. To use, simply adapt the component ColorPane
in your code, and pass the desired color along with the text in the method append
, as the user who is typing.
Follows the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class ChangeColorPaneTest extends JFrame {
JTextField field;
ColorPane pane;
boolean alternate = true;
public void startFrame() {
pane = new ColorPane();
pane.setBackground(new Color(245, 245, 245));
field = new JTextField();
field.setPreferredSize(new Dimension(getSize().width, 25));
field.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//action apenas para fins de exemplificação
Color textColor = alternate ? Color.red : Color.BLUE;
pane.append(textColor, field.getText());
alternate = !alternate;
field.setText("");
}
});
JScrollPane scrollpane = new JScrollPane(pane);
scrollpane.setPreferredSize(new Dimension(400, 200));
setTitle("ColorPane example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(scrollpane, BorderLayout.CENTER);
add(field, BorderLayout.PAGE_END);
field.requestFocusInWindow();
pack();
setVisible(true);
}
class ColorPane extends JTextPane {
public void append(Color c, String s) {
//implementação utilizando StyleContext
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
StyleConstants.Foreground, c);
// tamanho do texto já no component
int len = getDocument().getLength();
// altera a posicao do cursor para o fim(se não houver seleção)
setCaretPosition(len);
setCharacterAttributes(aset, false);
//O \n é apenas para o texto ser quebrado
//para fins de demonstracao
//se não houver seleção, adiciona o texto no fim
replaceSelection(s.concat("\n"));
}
}
public static void main(String argv[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
ChangeColorPaneTest pane = new ChangeColorPaneTest();
pane.startFrame();
}
});
}
}
Upshot:
Reference:
How to Use Editor Panes and Text Panes(Documentation)
What have you tried to do? Add to the question what you have done so far.
– user28595