How to get JEditorPane to display text as in JTextArea? - java

I want to make JEditorPane display the text as it is in the JTextArea. The reason for using JEditorPane is that I want to create links on specific text patterns (with a href). I have looked into JTextPane but did not find an easy way of doing it. The text is left padded, so the padding and the preserving the correct number of spaces is important. The difference between the display is shown below:
I want the JEditorPane to display the text exact same way as in JTextArea (on the left side). Maybe, there is another and better of way of doing it? Some text like 1233 will have links and associated event listeners will be triggered once I get the text display right.
The code:
import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
public class Test {
public static void main(String[] args)throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
final static String sampleText=
"\n" +
" 1233 2001/16/07 This is test\n" +
" With padding\n" +
" more padding\n" +
" and more padding";
private static void createAndShowGUI() {
final JFrame frame = new JFrame("test");
//final JTextComponent textComponent=new JTextArea();
final JEditorPane textComponent=new JEditorPane();
textComponent.setContentType("text/html");
textComponent.setFont(textComponent.getFont().deriveFont(11.5f));// larger font
textComponent.setText(sampleText);
frame.getContentPane().add(textComponent);
frame.setPreferredSize(new Dimension(370,120));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
This can be a solution when using plain text:
textComponent.setFont(new JTextArea().getFont().deriveFont(11.5f));
but formatting is lost. So, this does not work when I set the contentType to "text/html". The JEditorPane when I set the contenttype (even with Monospaced font):

Solution is, no matter what textComponent is (whether JTextArea or JEditorPane):
textComponent.setFont(new JTextArea().getFont().deriveFont(11.5f));
This forces JEditorPane to use the same font as JTextArea. Additionally, replace spaces with html entities and newlines with <br>:
sampleText=sampleText.replaceAll("\n","<br>").replaceAll("\\s"," ");

Related

How to vertically align text to the right of some text using javax.swing*;

How can I align text using Javax.swing. as the numbers are aligned in the pic:
You can achieve it with using HTML and JLabel. It allows you to insert tabulators in your text. To make them visible you have to use <pre></pre> tags. Consider this code, hope it helps.
public class Main extends JFrame {
JLabel text;
public Main() {
String html = "<html><pre>xxxx\t\txxxx<br>xxxxxxxxxxxxxx\txxxx</pre></html>";
text = new JLabel(html);
text.setPreferredSize(new Dimension(200,200));
add(text);
pack();
setVisible(true);
}
public static void main (String [] args) {
new Main();
}
}

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);

change specific text color in java

i am wondering how can i change a specific text color in a sentence?
lets say HELLO WORLD...i wanted to change the WORLD into red color without altering the font color of HELLO..same exact thing on how to change the WORLD in to bold
i wanted to set these string in to a jtextarea but all i can find is something like this
JTextArea textbox = new JTextArea("hello world");
textbox.setForeground(Color.red)
these makes the whole sentence into red instead of only making WORLD into red?
Have a look at this this from the Oracle documentation on text components. A JTextArea will accept styling, but it will always apply styling across its entire contents. However, if you were to use a JTextPane, you could create any styling you wanted in your text using HTML.
Code to back up assertion:
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.html.HTMLEditorKit;
public class StyleTestApp {
public static void main(final String[] args) {
final JFrame f = new JFrame("test");
//f.getContentPane().add(new JTextArea("<html>HELLO <font size=\"3\" face=\"verdana\" color=\"red\">WORLD</font></html>"));
final JTextPane p = new JTextPane();
// the HTMLEditorKit is not enabled by default in the JTextPane class.
p.setEditorKit(new HTMLEditorKit());
p.setText("<html>HELLO <font size=\"3\" face=\"verdana\" color=\"red\">WORLD</font></html>");
f.getContentPane().add(p);
f.pack();
f.setVisible(true);
}
}

JTextArea show Caret while setEditable is false

How can I put Caret in JTextArea while setEditable is disabled?
A sample code when I need Caret to be visible:
public void run(){
JFrame frame = new JFrame();
JTextArea text = new JTextArea();
text.setEditable(false);
String line = "added line";
text.append(line);
text.setCaretPosition(text.getCaretPosition() + line.length());
frame.getContentPane().add(text);
frame.setSize(300,300);
frame.setVisible(true);
}
What I want to achieve is that, when the user types within TextArea, characters must not be displayed. Typed characters are redirected to OutputStream and appropriate InputStream is received which will be displayed within TextArea. This works fine, but Caret is hidden because of setEditable(false).
text.getCaret().setVisible(true) and/or text.getCaret().setSelectionVisible(true)
Well, I put here a code fragment which shows the caret but don't let edit the JTextArea. I hope it helps you. It's a little trick which plays with the focus of the text area, when focus is gained, the edition is disabled; but when it's losed, the edition it's possible. In this way, the user is unable to edit it but can see the caret.
public void run() {
JFrame frame = new JFrame();
final JTextArea text = new JTextArea();
text.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent fe) {
text.setEditable(true);
}
public void focusGained(FocusEvent fe) {
text.setEditable(false);
}
});
text.setEditable(true);
String line = "added line";
text.append(line);
text.setCaretPosition(text.getCaretPosition() + line.length());
frame.getContentPane().add(text);
frame.setSize(300,300);
frame.setVisible(true);
}
Notice that the user can move the caret, but he/she can't edit the text
I tried the solution originally proposed by StanislavL. However, other issues emerged. For example, after leaving the JTextArea and focusing back later, the caret would turn invisible again.
I suspect that caret was not implemented as most people would expect to behave. While I saw some authors proposing to re-implement the caret, I successfully achieved visible caret behavior with following small listener:
textArea.getCaret().setVisible(true);
textArea.getCaret().setSelectionVisible(true);
textArea.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
textArea.getCaret().setVisible(true);
textArea.getCaret().setSelectionVisible(true);
}
#Override
public void focusLost(FocusEvent e) {
textArea.getCaret().setSelectionVisible(true);
}
});
On example above, I decided to keep the selection visible even if one leaves the text area.

How can I display red text in a JTextArea?

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

Categories