java - Selecting text in JTextArea does not show any selection color -
i have piece of code in jtextarea
added jframe
. whenever user presses ↑ key content of jtextarea
should selected.
here code
import javax.swing.*; import java.awt.event.keyevent; import java.awt.event.keyadapter; public class selectiontest extends keyadapter { final jtextarea jtextarea; public static void main(string[] args) { new selectiontest(); } selectiontest() { jframe jframe=new jframe(); jframe.setlocationrelativeto(null); jframe.setdefaultcloseoperation(windowconstants.exit_on_close); jtextarea = new jtextarea("test 1-2-3"); jtextarea.addkeylistener(this); jframe.add(jtextarea); jframe.pack(); jframe.setvisible(true); } @override public void keypressed(keyevent e) { if( e.getkeycode() != keyevent.vk_up ) return; jtextarea.selectall(); } }
however observe nothing selected on pressing ↑ key, instead if change method keypressed
following, works.
@override public void keypressed(keyevent e) { if( e.getkeycode() != keyevent.vk_up ) return; swingutilities.invokelater(new runnable() { @override public void run() { jtextarea.selectall(); } }); }
i want know reason behaviour. threading issue ?
jtextarea
uses arrow keys moving caret. you're interfering it. why invokelater()
helps.
also, have make sure component focusable , has focus. key listener lower level interface. mention above in comments, better use key bindings instead. see how use key bindings details , examples.
here example based on posted code uses key bindings :
import javax.swing.*; import java.awt.event.actionevent; import java.awt.event.keyevent; import java.awt.event.keyadapter; public class selectiontest extends keyadapter { final jtextarea jtextarea; public static void main(string[] args) { new selectiontest(); } selectiontest() { jframe jframe=new jframe(); jframe.setlocationrelativeto(null); jframe.setdefaultcloseoperation(windowconstants.exit_on_close); jtextarea = new jtextarea("test 1-2-3"); action someaction = new abstractaction() { public void actionperformed(actionevent e) { jtextarea.selectall(); } }; jtextarea.getinputmap().put( keystroke.getkeystroke(keyevent.vk_up, 0), "someaction"); jtextarea.getactionmap().put("someaction", someaction); jframe.add(jtextarea); jframe.pack(); jframe.setvisible(true); } }
also note if text area looses focus may not show selection. may need add jtextarea.requestfocusinwindow()
before altering selection. there selectall()
may use select text. see bug 4320295 : select , selectall don't work on jtextarea details.
Comments
Post a Comment