that is the text in the first textarea remain selected (text is in hightlight), when user is selecting text in the second one
I assume you mean the user is selecting different pieces of text in the two different text areas.
By default text components only show the selected text when the text component has focus.
The simple answer is to create a custom Caret and override the focusLost(...)
method and invoke setSelectionVisible(true)
at the end of the method to make sure the selection is painted even when the text component doesn't have focus.
Here is a fancier version of that approach that will allow you to specify a different selection background Color for the text component that doesn't have focus (if you wish):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class SelectionCaret extends DefaultCaret
{
private static final Color SELECTION_COLOR = UIManager.getColor("TextField.selectionBackground");
private Highlighter.HighlightPainter focusedPainter;
private Highlighter.HighlightPainter unfocusedPainter;
public SelectionCaret()
{
this(SELECTION_COLOR);
}
public SelectionCaret(Color unfocusedColor)
{
focusedPainter = new DefaultHighlighter.DefaultHighlightPainter(SELECTION_COLOR);
unfocusedPainter = new DefaultHighlighter.DefaultHighlightPainter(unfocusedColor);
setBlinkRate( UIManager.getInt("TextField.caretBlinkRate") );
}
@Override
protected Highlighter.HighlightPainter getSelectionPainter()
{
return getComponent().hasFocus() ? focusedPainter : unfocusedPainter;
}
@Override
public void focusGained(FocusEvent e)
{
setSelectionVisible(false);
super.focusGained(e);
}
@Override
public void focusLost(FocusEvent e)
{
super.focusLost(e);
setSelectionVisible(true);
}
private static void createAndShowUI()
{
JTextField textField1 = new JTextField("Text Field1 ");
JTextField textField2 = new JTextField("Text Field2 ");
JTextField textField3 = new JTextField("Non Editable ");
textField3.setEditable(false);
textField1.setCaret(new SelectionCaret());
textField2.setCaret(new SelectionCaret());
textField3.setCaret(new SelectionCaret());
textField1.select(5, 11);
textField2.select(5, 11);
textField3.select(5, 11);
((DefaultCaret)textField1.getCaret()).setSelectionVisible(true);
((DefaultCaret)textField2.getCaret()).setSelectionVisible(true);
((DefaultCaret)textField3.getCaret()).setSelectionVisible(true);
JPanel north = new JPanel();
north.add( new JTextField("Text Field0 ") );
north.add(textField1);
north.add(textField2);
north.add(textField3);
JFrame frame = new JFrame("Selection Caret");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( north );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
The above code was based on the code provided by mKorbel in this posting.