java怎样在JTextArea里选中一个文本内容

就是相当于鼠标选中,把特定字符串变成蓝的,可以修改。有什么方法能用吗,类似于记事本里的查找功能

可以这样试试

 import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class zz {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(300, 200);

        JTextArea textArea = new JTextArea();
        textArea.setText("Hello world! This is a test text.");
        textArea.setEditable(true);

        int start = textArea.getText().indexOf("world");
        int end = start + "world".length();
        textArea.select(start, end);
        textArea.setSelectionColor(Color.BLUE);

        textArea.replaceSelection("JAVA");

        frame.add(textArea);
        frame.setVisible(true);
    }

}


试下以下代码

JTextArea textArea = new JTextArea();
textArea.setText("Hello, world!");

// 选中某个字符串
textArea.requestFocus();
textArea.select(0, 5); // 从第0个字符开始,选中5个字符

// 将选中的字符串变成蓝色
textArea.setSelectionColor(Color.BLUE);

// 修改选中的字符串
textArea.replaceSelection("HELLO");

JTextArea本身不具备这样的功能,它是纯文本组件,你可以使用JTextPane,通过操作Document文档来控制JTextPane显示的内容

 import   javax.swing.*;   
  import   java.awt.*;   
  import   java.awt.event.*;   
  import   javax.swing.text.*;   
  import   java.io.*;   
    
  public   class   Test   {   
      JFrame   frame;   
      JTextPane   textPane;   
      File   file;   
      Icon   image;   
    
      public   Test(){   
          frame   =   new   JFrame("JTextPane");   
          textPane   =   new   JTextPane();   
          file   =   new   File("./classes/test/icon.gif");   
          image   =   new   ImageIcon(file.getAbsoluteFile().toString());   
      }   
    
      public   void   insert(String   str,   AttributeSet   attrSet)   {   
          Document   doc   =   textPane.getDocument();   
          str   ="\n"   +   str   ;   
          try   {   
              doc.insertString(doc.getLength(),   str,   attrSet);   
          }   
          catch   (BadLocationException   e)   {   
              System.out.println("BadLocationException:   "   +   e);   
          }   
      }   
    
      public   void   setDocs(String   str,Color   col,boolean   bold,int   fontSize)   {   
          SimpleAttributeSet   attrSet   =   new   SimpleAttributeSet();   
          StyleConstants.setForeground(attrSet,   col);   
          //颜色   
          if(bold==true){   
              StyleConstants.setBold(attrSet,   true);   
          }//字体类型   
          StyleConstants.setFontSize(attrSet,   fontSize);   
          //字体大小   
          insert(str,   attrSet);   
      }   
    
      public   void   gui()   {   
          textPane.insertIcon(image);   
          setDocs("第一行的文字",Color.red,false,20);   
          setDocs("第二行的文字",Color.BLACK,true,25);   
          setDocs("第三行的文字",Color.BLUE,false,20);   
          frame.getContentPane().add(textPane,   BorderLayout.CENTER);   
          frame.addWindowListener(new   WindowAdapter()   {   
              public   void   windowClosing(WindowEvent   e)   {   
                  System.exit(0);   
              }});   
          frame.setSize(200,300);   
          frame.setVisible(true);   
      }   
      public   static   void   main(String[]   args)   {   
          Test   test   =   new   Test();   
          test.gui();   
      }   
  } 

  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/679386
  • 同时,你还可以查看手册:java-国际化 - 介绍如何设计软件,使其能够轻松适应(本地化)各种语言和地区。-与文本打交道》提供了以独立于本地的方式操作文本的技术。-用JTextComponent类处理双向文本 中的内容
  • 除此之外, 这篇博客: 【Java笔记】给JTextArea添加滚动条中的 方法一: 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 直接将JTextArea放进JScrollPane,再将JScrollPane加到JFrame里

    	JFrame frame = new JFrame();//创建一个JFrame窗体
    	frame.setBounds(100, 100, 400, 200);//自定义Jframe位置并设置大小为100*50
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//用于关闭窗体
    	frame.getContentPane().setLayout(null);//设置为绝对布局
    	
    	JTextArea text1= new JTextArea("置换结果显示区域");//创建一个JTextArea,这里不必设置大小
    	JScrollPane scrollpane=new JScrollPane();//创建滚动条面板
    	scrollpane.setBounds(20,20,100,50);//自定义该面板位置并设置大小为100*50
    	
    	scrollpane.setViewportView(text1);//(这是关键!不是用add)把text1组件放到滚动面板里
    	frame.add(scrollpane);//将滚动条面板加到窗体
    	frame.setVisible(true);//放在最后,让整个窗体可视
    

    △下面是JScrollPane.setViewportView(Component view)的API:

    Creates a viewport if necessary and then sets its view. Applicationsthat don’t provide the view directly to the JScrollPaneconstructorshould use this method to specify the scrollable child that’s goingto be displayed in the scrollpane. For example:

         JScrollPane scrollpane = new JScrollPane();
         scrollpane.setViewportView(myBigComponentToScroll);

    Applications should not add children directly to the scrollpane.

    也就是:不直接为JScrollPane构造方法提供视图的应用程序,应使用setViewportView()这种方法,指定将显示在滚动窗格中的滚动组件子级。应用程序不应将子级直接添加到滚动窗格。


    △不能用JScrollPane.add(JTextArea),这是无法将JTextArea真正加入到滚动条面板中去的。下面是JScrollPane.add(comp)的API:

    Appends the specified component to the end of this container.This is a convenience method for addImpl.

    This method changes layout-related information, and therefore,invalidates the component hierarchy. If the container has already beendisplayed, the hierarchy must be validated thereafter in order todisplay the added component.

    也就是:将指定的组件附加到此容器的末尾。这是AddImpl的一种方便方法。此方法更改布局相关信息,因此使组件层次结构无效。如果容器已被禁用,则必须在此后验证层次结构,以便显示添加的组件。


  • 以下回答由chatgpt基于相关博客总结生成:

    可以通过使用JTextComponent类中的select方法来实现文本选中的功能。同时,可以设置选定文本的背景色和前景色来实现文本突出显示的效果。

    具体实现步骤如下:

    1.创建一个JTextArea并将其或将其添加到JScrollPane中,参考资料中给出了示例代码。

    2.在用户输入关键字后,可以使用JTextArea.getText()方法获取文本内容,进而使用String的相关方法来查找关键字在文本中的位置。

    3.使用JTextArea.setCaretPosition(int pos)方法将插入符号设置为关键字所在位置,然后使用JTextArea.select(int start, int end)方法将文本选中。

    4.调用JTextArea.setSelectionColor(Color color)和JTextArea.setSelectedTextColor(Color color)方法分别设置选定文本的背景色和前景色。

    示例代码如下:

    JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);
    // textAreascrollPane添加到容器中
    
    // 在用户输入关键字后执行以下代码
    String text = textArea.getText();
    String keyword = "关键字";
    int index = text.indexOf(keyword);
    if (index >= 0) {
        int end = index + keyword.length();
        textArea.setCaretPosition(end);
        textArea.select(index, end);
        textArea.setSelectionColor(Color.YELLOW);
        textArea.setSelectedTextColor(Color.RED);
    }
    

    需要注意的是,JTextArea只支持unstyled text,即不支持富文本格式,因此在更改选定文本的外观时只能设置背景色和前景色。另外,涉及到UI相关的操作一般都应该在Event Dispatch Thread中执行,可以使用SwingUtilities.invokeLater()方法来实现。

    如果需要在文本中有多个关键字,则可以使用循环来依次选定文本和设置背景色和前景色。如果需要实现类似于记事本的“查找下一个”功能,则可以在查找到第一个关键字后保存其位置,然后在点击“查找下一个”按钮时从该位置继续查找下一个关键字。