有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java jLabel在点处获取文本

我有一个JLabel,我想使用鼠标侦听器在特定位置获取文本,因此我想在JLabel上的点上获取单词

我不确定我是否能够使用其他东西而不是jLabel,因为我需要html兼容性和其他条件

我曾经尝试过使用jTextArea,但我猜它没有按需要工作(我有一段时间没有参与该项目)。有人能帮我吗


共 (1) 个答案

  1. # 1 楼答案

    我不认为你可以用JLabel做到这一点,但是可以用JTextComponent(比如JTextArea)实现,这要感谢viewToModel()方法,它:

    将视图坐标系中的给定位置转换为模型中最近的代表性位置

    所以,在你的内心MouseListener

    public void mouseClicked(MouseEvent e) {
       int index = textArea.viewToModel(new Point(e.getX(), e.getY()));
       String text = textArea.getText();
       String word = "";
       int i = index;
       while(isWordChar(text.charAt(i))) // Get text after the index
          word += text.charAt(i++);
       i = index-1;
       while(isWordChar(text.charAt(i))) // Get text before the index
          word = text.charAt(i ) + word;
    }