Java,在 JEditorPane 中精确选择文本

标签 java swing user-interface netbeans jeditorpane

我正在使用jEditorPane来充当一些编辑器,那个向我提出这个要求的人,也需要一个查找替换搜索......所以我想让他在查找和然后根据需要进行更换。

所以我提供这个简单的代码:

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    int start = (jEditorPane1.getSelectionStart()>jEditorPane1.getSelectionEnd())?jEditorPane1.getSelectionEnd():jEditorPane1.getSelectionStart();

    int max = (start>jEditorPane1.getSelectionStart())?start:jEditorPane1.getSelectionStart();

    String searchWord = jTextField3.getText();
    int searchIndex = jEditorPane1.getText().indexOf(searchWord, max);
    if(searchIndex != -1){
        jEditorPane1.select(searchIndex, searchIndex+searchWord.length());
    }
    else{
        jEditorPane1.setSelectionStart(-1);
        jEditorPane1.setSelectionEnd(-1);
    }
}       

幸运的是,应用程序返回了良好的索引,但不幸的是,在 View 窗口中我看不到任何选择。

我也是java新手,请帮忙

<小时/> PS。按钮 Action 由netbeans本身提供

<小时/>

您请求的样本

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * test.java
 *
 * Created on Jun 12, 2013, 8:23:19 PM
 */
package wordchecker;

/**
 *
 * @author Hassan
 */
public class test extends javax.swing.JFrame {

    /** Creates new form test */
    public test() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(jTextPane1);

        jTextField1.setText("jTextField1");

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        int startFrom = jTextPane1.getSelectionStart();
        if(jTextPane1.getSelectionStart() == jTextPane1.getSelectionEnd()){
            startFrom = -1;
        }

        String searchWord = jTextField1.getText();
        int searchIndex = jTextPane1.getText().indexOf(searchWord, startFrom);
        if(searchIndex != -1){
            jTextPane1.select(searchIndex, searchIndex+searchWord.length());
        }
        else{
            jTextPane1.setSelectionStart(0);
            jTextPane1.setSelectionEnd(0);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new test().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration
}

最佳答案

文本组件的选择仅在文本组件具有焦点时显示。当您单击该按钮时,它会获得焦点,因此您看不到文本选择。您可以使按钮不可聚焦,或者可以将以下内容添加到 actionPerformed() 方法的底部:

jTextPane1.requestFocusInWindow();

另外,不要使用 getText() 方法。这将导致偏移问题。

int searchIndex = jTextPane1.getText().indexOf(searchWord, startFrom);

参见Text and New Lines获取更多信息和解决方案。此链接的基础知识是使用:

int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);

上面只会返回“\n”作为 EOL 字符串,因此当您进行搜索然后选择文本时,偏移量将匹配。

编辑:

我通常使用如下代码:

int startFrom = jTextPane1.getCaretPosition();

关于Java,在 JEditorPane 中精确选择文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17069214/

相关文章:

java - JFrame 的 keylistener 和 actionlistener

c# - 哪些软件选项可用于原型(prototype)设计和创建 C++ 或 C# 桌面应用程序 GUI?

python - 如何获取 FFMPEG Progress 以创建进度条?

java - 停止maven安装

java - 在 Spring boot 中使用 mysql join 作为一个 java 对象返回两个表的数据

java - 在 Jira 插件的速度模板方面需要一些帮助

user-interface - 增加这个简单的 go gui 应用程序的默认字体大小

java - 如何使用列表在 JasperReports 中生成动态表

java - 如何在鼠标位置添加面板?

java - 如何使 jPanel 可滚动