简体   繁体   中英

Java, select text Exactly in JEditorPane

I'm using jEditorPane to act kinda as some editor, the one who asked for this of me, also needed a find replace search... so I wanted to let him select in find and then do replace on need.

so I provide this simple code:

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

fortunatelly the application return good indexes, but unfortunatelly on view windows I see no selection.

I'm also new to java, please help


PS. buttons action are provided by netbeans itself


THe sample you requested

/*
 * 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
}

The selection of a text component is only displayed when the text component has focus. When you click on the button it gains focus so you don't see the text selection. You could make the button non-focusable or you can add the following to the bottom of your actionPerformed() method:

jTextPane1.requestFocusInWindow();

Also, don't use the getText() method. This will cause problems with offsets.

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

See Text and New Lines for more information and a solution. The basics of this link is to use:

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

The above will only return "\\n" as the EOL string so the offsets will match when you do a search and then select the text.

Edit:

I generally use code like the following:

int startFrom = jTextPane1.getCaretPosition();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM