To get color text on the TextArea

ehmaster

Mitglied
Hello dear java community,


How is it possible to get color text on the textArea when i have an actionPerformed for my button. After button action i want to see a color text on the TextArea.


Thank you in advance.




Java:
addBt.addActionListener(new ActionListener() {


			@Override
			public void actionPerformed(ActionEvent arg0) {


				String text = "ascascas: " + " \n" + "acaca is: " + ""
						+ "200" + "    " + "/   " + "ascasca is:" + " "
						+ "" + "\n";


				fireDetailEvent(new DetailEvent(this, text));


			}


		});
 
As far as I know it is not possible to do this with a JTextArea. However you can definitely do this with a JTextPane. I used the code from this StackOverflow post and made a small example:

Java:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;



public class Start
{	
	public static void main(String[] args)
	{
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run()
			{
				JFrame frame = new JFrame("Test Frame");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				
				JPanel panel = new JPanel();
				JTextPane tPane = new JTextPane();
				
				appendToPane(tPane, "My Text Green\n", Color.GREEN);
				appendToPane(tPane, "Some Orange Text", Color.ORANGE);
				appendToPane(tPane, "Other Text Blue", Color.BLUE);
				
				panel.add(tPane);
				frame.add(panel);
				
				frame.pack();
				frame.setLocationRelativeTo(null);
				frame.setVisible(true);
			}
			
		});
		
	}
	
	private static 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);
    }
}
 

Zurück
Oben