简体   繁体   English

单击JButton设置文本样式后保持选择

[英]Keeping selection after clicking a JButton to style text

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 toolbar look quite bad. 我尝试使用JMenuItem而不是JButton来运行,但这似乎起作用了,但是随后它使我的工具栏看起来非常糟糕。 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. 任何帮助表示赞赏。

因此,我想知道是否存在允许我单击按钮但保留选择的设置?

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 . 您需要使用requestFocus重新设置焦点。 However, you will need to write your own action listener to add the focus code - you could extend BoldAction to do this. 但是,您将需要编写自己的动作侦听器以添加焦点代码-您可以扩展BoldAction来执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM