Похоже, что вы должны использовать это JTextPane / JEditorPane , для изменения цвета случайных строковых литералов попробуйте этот код, кажется, это то, что вы хотели: -)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class TextPaneTest extends JFrame
{
private JPanel topPanel;
private JTextPane tPane;
private JTextField tfield;
private String username = null;
public TextPaneTest()
{
topPanel = new JPanel();
topPanel.setLayout(new BorderLayout(5, 5));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));
tPane = new JTextPane();
tPane.setBorder(eb);
//tPane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
tPane.setMargin(new Insets(5, 5, 5, 5));
JScrollPane scrollPane = new JScrollPane(tPane);
topPanel.add(scrollPane, BorderLayout.CENTER);
tfield = new JTextField(10);
tfield.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (tfield.getDocument().getLength() > 0)
{
appendToPane(tPane, username + " : ", Color.MAGENTA);
appendToPane(tPane, tfield.getText() + "\n", Color.DARK_GRAY);
tfield.selectAll();
}
}
});
topPanel.add(tfield, BorderLayout.PAGE_END);
getContentPane().add(topPanel);
setSize(200, 100);
setVisible(true);
while (username == null)
{
username = JOptionPane.showInputDialog(null, "Please Enter USERNAME : ");
}
tfield.requestFocusInWindow();
}
private void appendToPane(JTextPane tp, String msg, Color c)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
int len = tp.getDocument().getLength();
tp.setCaretPosition(len);
tp.setCharacterAttributes(aset, false);
tp.replaceSelection(msg);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextPaneTest();
}
});
}
}