javaswingjtextfieldjtextpanejtextcomponent

JTextPane select() not working if JTextFeild is in JFrame


I am trying to select some text programmatically in a JTextPane but it isn't working. I found out the problem but I don't know how to fix it. It works fine if there is no JTextFeild in the JFrame but if I add it, the focus goes to the JTextFeild and the selection unselects.

Here is an SSCCE

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;


@SuppressWarnings("serial")
public class SSCCE extends JFrame {

    JTextPane pane;
    JTextField feild;

    public SSCCE() {
        setSize(300, 200);
        feild = new JTextField("This is a text feild");
        // Run the program then uncomment the next line and run the program again.
        // add(feild, BorderLayout.NORTH);
        pane = new JTextPane();
        pane.setText("This is some text. I am making an SSCCE. This is some additional text.");
        pane.select(2, 30);
        add(pane);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new SSCCE();
    }
}

Solution

  • Another Solution instead of requestFocusInWindow is a Highlighter like this:

    public class SSCCE extends JFrame {
    
    JTextPane pane;
    JScrollPane scrollPane;
    JTextField feild;
    
    public SSCCE() throws BadLocationException {
        setSize(300, 200);
        feild = new JTextField("This is a text feild");
        // Run the program then uncomment the next line and run the program
        // again.
        add(feild, BorderLayout.NORTH);
        pane = new JTextPane();
        pane.setFocusable(true);
        pane.setText("This is some text. I am making an SSCCE. This is some additional text.");
        pane.getHighlighter().addHighlight(2, 30,
                new DefaultHighlighter.DefaultHighlightPainter(Color.LIGHT_GRAY));
        scrollPane = new JScrollPane(pane);
        add(scrollPane, BorderLayout.CENTER);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    
    }
    
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new SSCCE();
                } catch (BadLocationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
    }