开发者

Keeping selection after clicking a JButton to style text

开发者 https://www.devze.com 2023-01-25 22:30 出处:网络
I\'m making a fairly simple text editor, and I have a question about my style buttons. When I highlight text and click my \"bold\" button, the text bolds as expected, but my selection is not longer vi

I'm making a fairly simple text editor, and I have a question about my style buttons. When I highlight text and click my "bold" button, the text bolds as expected, but my selection is not longer visible. I can still unbold the selection, italicize it, or underline it, but you just can't see what is selected. So, I'm wondering if there is a setting that will allow me to click the button, but keep my selection? I tried a JMenuItem instead of a JButton, and that seemed to work, but then it made my t开发者_运维问答oolbar look quite bad. Sample code below.

//frame and pane creation up here
JToolBar tool = new JToolBar();
JToggleButton boldButton = new JToggleButton("Bold");
boldButton.addActionListener(new StyledEditorKit.BoldAction());
tool.add(boldButton);

Any help is appreciated.


So, I'm wondering if there is a setting that will allow me to click the button, but keep my selection?

boldButton.setFocusable( false );


As you noticed, the selection is still there but clicking on the toolbar button removes the focus from the text pane and hides the selection. You need to set the focus back using requestFocus. However, you will need to write your own action listener to add the focus code - you could extend BoldAction to do this.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号