单击 JButton 设置文本样式后保持选择
我正在制作一个相当简单的文本编辑器,我对我的样式按钮有疑问。当我突出显示文本并单击“粗体”按钮时,文本会按预期粗体显示,但我的选择不再可见。我仍然可以取消所选内容的粗体、斜体或下划线,但您只是看不到所选内容。所以,我想知道是否有一个设置可以让我单击按钮,但保留我的选择?我尝试使用 JMenuItem 而不是 JButton,这似乎有效,但随后它使我的工具栏看起来很糟糕。下面的示例代码。
//frame and pane creation up here
JToolBar tool = new JToolBar();
JToggleButton boldButton = new JToggleButton("Bold");
boldButton.addActionListener(new StyledEditorKit.BoldAction());
tool.add(boldButton);
任何帮助表示赞赏。
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. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您所注意到的,选择仍然存在,但单击工具栏按钮会将焦点从文本窗格中删除并隐藏选择。您需要使用
requestFocus
。但是,您需要编写自己的操作侦听器来添加焦点代码 - 您可以扩展BoldAction
来执行此操作。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 extendBoldAction
to do this.