change specific text color in java - 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);
}
}

Related

Java Jdatechooser Foreground

good day
I am trying to change the color of the box text (jtextfile) that brings the built-in jdatechooser
I am developing an application where the white background of the jdatechooser does not match at all, I have changed the background color of both the jtextfile and the button of the jdatechooser with the following code:
for( Component c : jdate.getComponents()){
((JComponent)c).setBackground(new Color(20,25,34));
}
thus
My current problem is that the background color that I need is very dark, and the date text is black, currently in the image there is a selected date, you just don't see anything.
I have tried to change the text to white without success.
try the same method without getting the solution
for( Component text : jdate.getComponents()){
((JComponent)text).setForeground(new Color(255,255,255));
}
I also tried removing the code that I put at the beginning for the background thinking that this could be preventing the change of the text color but it did not work either.
Try these other ways to get the change:
JTextFieldDateEditor dateChooserEditor = ((JTextFieldDateEditor)jdate.getDateEditor());
dateChooserEditor.setForeground(new Color(255, 255, 255));
Of course the easy way didn't work either:
jdate.setForeground(Color.WHITE);
The only way I have managed to change the color of the text is to disable the text field and leave the button enabled to choose the date for the button and it cannot be written in the text box.
jdate.getDateEditor().setEnabled(false);
((JTextFieldDateEditor) jdate.getDateEditor ())
.setDisabledTextColor(Color.WHITE);
The problem with this, in addition to not being allowed to write the date manually, I also lose the desired background color.
as shown here
Any solution for this ?, preferably without having to disable the text box.
Thanks in advance!.
I propose the following solution.
Class JTextFieldDateEditor extends JFormattedTextField. Hence the foreground color is a bound property which means that you can listen for changes to it. Therefore you can add a PropertyChangeListener. If the new foreground color is black, simply change it to white.
Here is a small application that demonstrates.
import com.toedter.calendar.IDateEditor;
import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JTextFieldDateEditor;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class JdcTest0 implements Runnable {
private JFrame frame;
private JDateChooser jdate;
#Override
public void run() {
showGui();
}
private JPanel createDateChooser() {
JPanel panel = new JPanel();
jdate = new JDateChooser();
IDateEditor dateEditor = jdate.getDateEditor();
if (dateEditor instanceof JTextFieldDateEditor) {
JTextFieldDateEditor txtFld = (JTextFieldDateEditor) dateEditor;
txtFld.setBackground(Color.BLACK);
txtFld.addPropertyChangeListener("foreground", event -> {
if (Color.BLACK.equals(event.getNewValue())) {
txtFld.setForeground(Color.WHITE);
}
});
}
panel.add(jdate);
return panel;
}
private void showGui() {
frame = new JFrame("JDC");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createDateChooser(), BorderLayout.PAGE_START);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new JdcTest0());
}
}
Note that class JTextFieldDateEditor changes its foreground color to red if the date is invalid and to green if the date is valid. If you want to handle those colors as well, then the red color is java.awt.Color#red, i.e. [255, 0, 0] and the green is a custom color [0, 150, 0].

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 get JEditorPane to display text as in JTextArea?

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

Adding JScrollPane in Netbeans visual editor

I have designed a window using Netbean's visual editor. Now, I have a JTextField, which I want to add using a Scroll bar. How can I do that?
You should not add Scollbar to a TextField.TextField is meant for inputting small entries from the user like name,age,roll number,etc.The best component to input large sized texts ,like comments, from user is JTextArea.So You must add JTextArea instead of JTextField.
After adding JTextArea to the JFrame,you can write few lines of code:-
JScrollPane jsc=new JScrollPane();
jsc.add(jta);
where 'jta' is the name of your JTextArea which your Netbeans have generated for you.
(Now ,when you add text greater than the limit size of text Area ,the scrollbars will appear.
If you want the scrollbars appear permanently,then,the JScrollPane has two properties: horizontalScrollBarPolicy and verticalScrollBarPolicy. Set this two properties to ALWAYS and you will see the Scroll bars always irrespective the size of text in JTextArea.)
Here is the complete code to demonstrate you what you can do:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class TextAreaDemo
{
JTextArea jta;
TextAreaDemo()
{
JFrame jfrm=new JFrame("Text Area");
jfrm.setSize(200,300);
jfrm.getContentPane().setLayout(new FlowLayout());
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jta=new JTextArea("Type Here");
//You can use this line to wrap that text when it extends on right side.
//jtxt.setLineWrap(true);
JScrollPane jscrp=new JScrollPane(jta);
jscrp.setPreferredSize(new Dimension(180,100));
jscrp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jfrm.add(jscrp);
jfrm.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){public void run(){new TextAreaDemo();}});
}
}
Use JTextArea and put this into a JScrollPane. If you are using the visual editor it will be done by default (dropping the TextArea into your Window). The JScrollPane has two properties: horizontalScrollBarPolicy and verticalScrollBarPolicy. Set this two properties to ALWAYS and you will see the Scroll bars.

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