Java JTextArea中选择文本触发哪个事件? [英] Which event a selection of text trigger in Java JTextArea?
本文介绍了Java JTextArea中选择文本触发哪个事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想监视JTextArea中文本的选择.我不知道选择文本触发会发生什么情况.
I want to monitor the selection of text into the a JTextArea. I don't know what event a selection of text triggers.
我只想在从JTextArea中选择了某些文本(例如在菜单中复制和剪切选项)后立即启用某些菜单项.我应该为此监视什么?
I just want to enable some of the menu items as soon as some text is selected out of the JTextArea like copy and cut options into the menu. What should I monitor for that?
推荐答案
我不知道文本组件的任何选择侦听器"(尽管它们可能有用),但是您可以使用CaretListener
来监视更改到插入符号位置并检查选择状态...
I don't know about any "selection listeners" for text components (although they might be useful), but you could use a CaretListener
to monitor changes to the caret position and check the selection state...
public class TestSelectionMonitor {
public static void main(String[] args) {
new TestSelectionMonitor();
}
public TestSelectionMonitor() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JTextArea ta = new JTextArea();
ta.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
int length = ta.getSelectionEnd() - ta.getSelectionStart();
System.out.println(length);
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(ta));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
这篇关于Java JTextArea中选择文本触发哪个事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文