How can I display red text in a JTextArea? - java

I want to show error(text) in result in red color after compiling exec file
and display it in textarea of gui using swing in java.

A normal JTextArea doesn't support fancy things like different colors of text. However, there are similar components that do. See http://java.sun.com/docs/books/tutorial/uiswing/components/text.html

JEditorPane can get content formatted in HTML. The official Sun tutorial also gives some insight:
The JTextArea class provides a component that displays multiple lines of text and optionally allows the user to edit the text. If you need to obtain only one line of input from the user, you should use a text field. If you want the text area to display its text using multiple fonts or other styles, you should use an editor pane or text pane. If the displayed text has a limited length and is never edited by the user, use a label.

Here's a quick example of adding text to a JEditorPane using AttributeSet and StyleConstants.
This brings up a little frame with a JEditorPane and you can use it to add text of lots of colors without using HTML.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
public class TextColor extends JFrame implements ActionListener {
JTextPane myTextPane;
JTextArea inputTextArea;
public TextColor() {
super();
JPanel temp = new JPanel(new BorderLayout());
inputTextArea = new JTextArea();
JButton btn = new JButton("Add");
btn.addActionListener(this);
temp.add(btn, BorderLayout.SOUTH);
temp.add(inputTextArea, BorderLayout.NORTH);
this.getContentPane().add(temp, BorderLayout.SOUTH);
myTextPane = new JTextPane();
myTextPane.setBorder(new EtchedBorder());
this.getContentPane().add(myTextPane, BorderLayout.CENTER);
this.setSize(600, 600);
this.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Color newTextColor = JColorChooser.showDialog(this, "Choose a Color", Color.black);
//here is where we change the colors
SimpleAttributeSet sas = new SimpleAttributeSet(myTextPane.getCharacterAttributes());
StyleConstants.setForeground(sas, newTextColor);
try {
myTextPane.getDocument().insertString(myTextPane.getDocument().getLength(),
inputTextArea.getText(), sas);
} catch (BadLocationException ble) {
ble.printStackTrace();
}
}
public static void main(String args[]) {
new TextColor();
}
}

Smita,
take care to paste snippet of your code so that one can understand where exactly problem is or help is required.
Coming to your problem,
To the best of my knowledge, there is no way to set different colors for different text elements in textArea in java. You can set only one color for all.
Alternative is to use JTextPane.
See if following code helps your cause.
String text = "Some Text..."; //This can be any piece of string in your code like
output of your program...
JTextPane myTextPane = new JTextPane();
SimpleAttributeSet sas = new SimpleAttributeSet(myTextPane.getCharacterAttributes());
// As what error you were referring was not clear, I assume there is some code in your
program which pops out some error statement. For convenience I use Exception here..
if( text.contains("Exception") ) //Checking if your output contains Exception...
{
StyleConstants.setForeground(sas, Color.red); //Changing the color of
StyleConstants.setItalic(sas, true);
try
{
myTextPane.getDocument().insertString
(
myTextPane.getDocument().getLength(),
text + "\n",
sas
);
}
catch( BadLocationException ble )
{
text.append(ble.getMessage());
}
}
else
{
StyleConstants.setForeground(sas, Color.GREEN);
try
{
myTextPane.getDocument().insertString
(
myTextPane.getDocument().getLength(),
text + "\n",
sas
);
}
catch(BadLocationException ble)
{
text.append(ble.getMessage());
}
}
I guess this will solve your problem with few modifications.
Thanks.
Sushil

Related

How can I prevent JTextPane from resetting font settings if the initial text ends with a linefeed?

I've run into a problem with JTextPane. The code I am working with sets a number of font attributes, such as BOLD, ITALIC, etc. But if the initial text ends with a single linefeed, and the user clicks on the last line, or is sent to the last line, the default font settings appear for any additional text the user types.
Specifically, this text works as I would expect: jTextPane.setText(String.format("Test This"));.
This text does not:
jTextPane.setText(String.format("Test This%n%n%n"));
I think that JTextPane may consider this to be a new paragraph.
If so, I would like to either
a.) Know how to set a universal font that applies across the entire JTextPane instance's paragraphs.
or
b.) tell the JTextPane instance to consider all of its editable area to be one paragraph.
Here is a toy program to show you what I mean. If you run this, and start typing at the end of the text the font will be whatever the default is for your Swing implementation.
I have also tried setting the document model of the JTextPane and using a Font instance in the JTextPane constructor. The results are the same.
Another alternative is to use a JTextArea instance instead, but this is very complex code and I hesitate to make a change that may break some other area of the application than the one I am working in.
import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
public class JTextPaneExampleOne {
public static void main(String args[]) {
JFrame frame = new JFrame("JTextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frame.getContentPane();
JTextPane pane = new JTextPane();
String welcomeString = String.format("Welcome%n%n%nStranger!%n%n%n");
pane.setText( welcomeString );
pane.invalidate();
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setBold(attributeSet, true);
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.red);
pane.setSelectionStart( 0 );
pane.setSelectionEnd( pane.getText().length() );
pane.setParagraphAttributes( attributeSet, true );
pane.setSelectionStart( pane.getText().length() );
pane.validate();
JScrollPane scrollPane = new JScrollPane(pane);
cp.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
a.) Know how to set a universal font that applies across the entire JTextPane instance's paragraphs.
In this case, you might be able to use JTextPane#setLogicalStyle(Style):
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JTextPaneExampleOne2 {
public Component makeUI() {
JTextPane pane = new JTextPane();
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style body = pane.getStyledDocument().addStyle("body", def);
StyleConstants.setBold(body, true);
StyleConstants.setItalic(body, true);
StyleConstants.setForeground(body, Color.RED);
pane.setLogicalStyle(body);
String welcomeString = String.format("Welcome%n%n%nStranger!%n%n%n");
pane.setText(welcomeString);
// SimpleAttributeSet attributeSet = new SimpleAttributeSet();
// StyleConstants.setBold(attributeSet, true);
// StyleConstants.setItalic(attributeSet, true);
// StyleConstants.setForeground(attributeSet, Color.RED);
//
// pane.setSelectionStart(0);
// pane.setSelectionEnd(pane.getText().length());
// pane.setParagraphAttributes(attributeSet, true);
// pane.setSelectionStart(pane.getText().length());
return new JScrollPane(pane);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame("JTextPane Example");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new JTextPaneExampleOne2().makeUI());
f.setSize(400, 400);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}

How to disable text selection on JTextArea Swing

I don't want the user to select the content on JTextArea. I use setEditable(false) but it's not working. How to disable this feature of JTextArea component. Could you give me advise. Thanks.
If you would like to just disable text selection on any swing control such as JtextArea you can use the coding below:
JtextArea.setHighlighter(null);
This one line of coding will help disable the text selection and can be placed in the constructor or within a initialized method upon Frame execution.
Hope this helps
You can set the "mark" equal to the "dot" of the caret. When these values are equal there is no text selection:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class NoTextSelectionCaret extends DefaultCaret
{
public NoTextSelectionCaret(JTextComponent textComponent)
{
setBlinkRate( textComponent.getCaret().getBlinkRate() );
textComponent.setHighlighter( null );
}
#Override
public int getMark()
{
return getDot();
}
private static void createAndShowUI()
{
JTextField textField1 = new JTextField("No Text Selection Allowed");
textField1.setCaret( new NoTextSelectionCaret( textField1 ) );
textField1.setEditable(false);
JTextField textField2 = new JTextField("Text Selection Allowed");
JFrame frame = new JFrame("No Text Selection Caret");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(textField1, BorderLayout.NORTH);
frame.add(textField2, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Late to the party, but here are my findings. I had tried using setEnabled(false) on a JTextPane displaying static (not user-modifiable) content such as line numbers (for another text component). This one alone prevents the component from getting focus and text selection on it:
JTextArea textArea = new JTextArea("Static text");
textArea.setEnabled(false);
My problem with setEnabled(false) is that it forces a single disabledTextColor for all of the text (I've traced it down to javax.swing.text.GlyphView.paint()), while I want to style individual lines/chunks. I've finally tried setFocusable(false) that appears to satisfy both needs:
Not user focusable and no user selection on it;
Custom text color could be applied to individual parts of the content, or it just doesn't change the text color to the disabled one.
The complete solution needs additional setEditable(false) to prevent the mouse cursor from changing but that's it – two properties:
JTextArea textArea = new JTextArea("Static text");
textArea.setEditable(false);
textArea.setFocusable(false);

Scroll down automatically JTextArea for show the last lines added

I have written a Java application that receives information from a server every 10 seconds. I am wanting to display this information on a form.
Currently I am using a JTextArea. However, once the JTextArea is filled up, I cannot see the new information that is added to this JTextArea. Do I need to add scroll bars to the JTextArea? Or is there a completely new different control for GUI forms that is recommended to display information that is added every x seconds?
DefaultCaret tries to make itself visible which may lead to scrolling of a text component within JScrollPane. The default caret behavior can be changed by the DefaultCaret#setUpdatePolicy method.
Assumption that the name of your variable is textArea, you only need to modify the policy of caret:
DefaultCaret caret = (DefaultCaret) textArea.getCaret(); // ←
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); // ←
...
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(textArea);
* Thanks, mKorbel
Do I need to add scroll bars to the JTextArea?
Add the text area to a JScrollPane. See How to Use Scroll Panes for more information & examples.
Here is an example:
import java.awt.*;
import java.io.*;
import javax.swing.*;
class TextAreaScrolling {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
final JTextArea out =
new JTextArea(5,10); // suggest columns & rows
JScrollPane outScroll = new JScrollPane(out);
File f = new File("TextAreaScrolling.java");
try {
Reader reader = new FileReader(f);
out.read(reader, f);
} catch (Exception ex) {
ex.printStackTrace();
}
JOptionPane.showMessageDialog(null, outScroll);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}

How to create formatted text to show in a Java Swing Component (JTextPane, JEditorPane...)

I've searched and researched in everywhere I could to find an answer with no result. So I ask for help once more.
I want to show formatted text in a desktop java swing application. This text would be programactly generated in base of some variable objects and wouldn't be editable.
I don't know if is best to use JTextPane, or JEditorPane, or what. The matter is that I don't find anywhere some manual or tutorial that explain how to use them. Do I have to create an HTMLDocument to insert the text? How do I create it?...
Is is the right way to show text in this case?, or may I go using tables or labels or something like that.
I need some advice from you please, if there is some where I could learn how to do it, tell me please.
Here have a look at this code example, if you want to modify this a bit more, add Font too as an argument and use that appropriate argument at the specified location. Write something in the JTextField and press ENTER several times.
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 int counter;
private Color[] colours = {
Color.RED,
Color.BLUE,
Color.DARK_GRAY,
Color.PINK,
Color.BLACK,
Color.MAGENTA,
Color.YELLOW,
Color.ORANGE
};
public TextPaneTest() {
counter = 0;
}
private void createAndDisplayGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));
tPane = new JTextPane();
tPane.setBorder(eb);
tPane.setMargin(new Insets(5, 5, 5, 5));
JScrollPane scroller = new JScrollPane();
scroller.setViewportView(tPane);
tfield = new JTextField();
tfield.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
counter++;
if (counter == 8)
counter = 0;
String text = tfield.getText() + "\n";
appendToPane(tPane, text, colours[counter]);
tfield.selectAll();
}
});
getContentPane().add(scroller, BorderLayout.CENTER);
getContentPane().add(tfield, BorderLayout.PAGE_END);
setSize(200, 100);
setVisible(true);
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() {
#Override
public void run() {
new TextPaneTest().createAndDisplayGUI();
}
});
}
}
I've searched and researched in everywhere I could to find an answer with no result. So I ask for help once more.
everything is described with required details in the Oracle How to Use Editor Panes and Text Panes, including support for styled text
Do I have to create an HTMLDocument to insert the text? How do I create it?...
not you don't need to create a HTML contens, about HTML is Oracle tutorial How to Use HTML in Swing Components
Is is the right way to show text in this case?, or may I go using tables or labels or something like that.
for styled text is JEditorPane / JTextPane best of the choices
examples in the tutorial or here

change font of specific lines in JTextArea

hi there ı am working on a chat application and i want that user can change the font which he/she is writing. there is a setFont() function but it changes font of all strings in the TextArea. so i just want to change only my font.i appreciated if you can help me.
well then i guess i must learn a litte HTML
I wouldn't use HTML. I find it easier to just use attributes when dealing with a text pane. Attributes are much easier to change then trying to manipulate HTML.
SimpleAttributeSet green = new SimpleAttributeSet();
StyleConstants.setFontFamily(green, "Courier New Italic");
StyleConstants.setForeground(green, Color.GREEN);
// Add some text
try
{
textPane.getDocument().insertString(0, "green text with Courier font", green);
}
catch(Exception e) {}
You should work with JTextPane. JTextPane allows you to use HTML. Check the following example:
this.text_panel = new JTextPane();
this.text_panel.setContentType("text/html");
this.text_panel.setEditable(false);
this.text_panel.setBackground(this.text_background_color);
this.text_panel_html_kit = new HTMLEditorKit();
this.text_panel.setEditorKit(text_panel_html_kit);
this.text_panel.setDocument(new HTMLDocument());
Here you are enabling HTMLEditorKit, which will allow you to use HTML in your TextPane. Here is another peice of code, where you can add colored text to the panel:
public void append(String line){
SimpleDateFormat date_format = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
line = "<div><font size=3 color=GRAY>[" + date_format.format(date) + "]</font><font size=3 color=BLACK>"+ line + "</font></div>";
try {
this.text_panel_html_kit.insertHTML((HTMLDocument) this.text_panel.getDocument(), this.text_panel.getDocument().getLength(), line, 0, 0, null);
} catch (Exception e) {
e.printStackTrace();
}
}
Hope this helps,
Serhiy.
You can't do that with JTextArea, but you can do it with its fancier cousin, JTextPane. It's unfortunately not trivial; you can learn about this class here.
A variety of Swing components will render basic HTML (version 3.2), including JLabel & JEditorPane. For further details see How to Use HTML in Swing Components in the Java Tutorial.
Here is a simple example using the latter.
import java.awt.*;
import javax.swing.*;
class ShowFonts {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
String pre = "<html><body style='font-size: 20px;'><ul>";
StringBuilder sb = new StringBuilder(pre);
for (String font : fonts) {
sb.append("<li style='font-family: ");
sb.append(font);
sb.append("'>");
sb.append(font);
}
JEditorPane ep = new JEditorPane();
ep.setContentType("text/html");
ep.setText(sb.toString());
JScrollPane sp = new JScrollPane(ep);
Dimension d = ep.getPreferredSize();
sp.setPreferredSize(new Dimension(d.width,200));
JOptionPane.showMessageDialog(null, sp);
}
});
}
}

Categories