检测 JTextArea 中的文本选择
我有一个 JTextArea,正在检查是否有任何文本被选择,如果没有,则两个菜单项呈灰色。我遇到的问题是,当我编译并打开应用程序时,我必须先单击 JTextArea,然后菜单项就会变灰,如果不这样做,即使没有选择任何文本,菜单项也不会变灰。我正在使用以下插入符号侦听器。
textArea.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent arg0) {
int dot = arg0.getDot();
int mark = arg0.getMark();
if (dot == mark) {
copy2.setEnabled(false);
cut1.setEnabled(false);
}
else{
cut1.setEnabled(true);
copy2.setEnabled(true);
}
}
});
I have a JTextArea and am deteching if any text is selection, if none is then two of the menu items are grayed out. The problem I have is, when I compile and open the application I have to click on the JTextArea first and then then the menu items are greyed out, if I don't they aren't even if no text is selected. I am using the following caret listener.
textArea.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent arg0) {
int dot = arg0.getDot();
int mark = arg0.getMark();
if (dot == mark) {
copy2.setEnabled(false);
cut1.setEnabled(false);
}
else{
cut1.setEnabled(true);
copy2.setEnabled(true);
}
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建这些菜单项时,您应该对其进行
setEnabled(false)
。You should
setEnabled(false)
on each of these menu items when you create them.您可以在单独的函数中定义剪切/复制菜单项的启用/禁用逻辑,并在初始化 GUI 时调用该函数,并且该函数将在 CaretUpdate(或最好是 MouseReleased)事件上调用。
You can define enable/disable logic for cut/copy menu items in a separate function, and call that function while initializing GUI, and also that function will be called on CaretUpdate (or better be MouseReleased) event.
您可以使用
JtextField.setHighlighter(null);
You can use
JtextField.setHighlighter(null);