【问题标题】:JTextArea getting whole lineJTextArea 得到整行
【发布时间】:2010-09-08 15:23:47
【问题描述】:

我如何从 JTA 获得选择的线路?

【问题讨论】:

  • 你接受的方案效率不高。

标签: java jtextarea swing


【解决方案1】:

我想您可以使用 getLineStartOffset(int line) 和 getLineEndOffset(int line) 从 getText() 返回的字符串中提取特定行

如果您的意思是想知道用户选择了什么(使用鼠标/键盘): getSelectedText() 应该给你。

【讨论】:

  • +1,直接从 JTextArea API 获取更有效的解决方案。
【解决方案2】:

为什么不将这些行分成标记。那么如果你知道你想要的行号,你可以通过一个字符串数组来访问它

public class JTALineNum extends JFrame{
 JTextArea jta = null;
 JButton button = null;

 public JTALineNum(){
  jta = new JTextArea();
  button = new JButton("Hit Me");

  button.addActionListener(new ButtonListener());

  add(jta, BorderLayout.CENTER);
  add(button, BorderLayout.SOUTH);
  setSize(200,200);
  setVisible(true);
 }

 private class ButtonListener implements ActionListener{

  public void actionPerformed(ActionEvent e) {
   String text = jta.getText();
   String[] tokens = text.split("\n");
   for(String i : tokens){
    System.out.println("Token:: " + i);
   }
  }
 }

 public static void main(String args[]){
  JTALineNum app = new JTALineNum();
  app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 2012-08-21
    • 2013-12-16
    相关资源
    最近更新 更多