2013-02-28 40 views

回答

5

我不知道任何“选择侦听器”文本组件(尽管它们可能是有用的),但你可以使用一个CaretListener监视更改插入符位置,并检查选择状态...

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); 
      } 
     }); 
    } 
} 
+0

YUP ...正常工作... 非常感谢好友...... !!! – 2013-02-28 22:55:44

相关问题