如果JTextFeild在JFrame中,则JTextPane select()不起作用

时间:2014-05-17 15:04:23

标签: java swing jtextfield jtextpane jtextcomponent

我试图在JTextPane中以编程方式选择一些文本,但它不起作用。我发现了问题,但我不知道如何解决它。如果JFrame中没有JTextFeild,它可以正常工作,但如果我添加它,焦点将转移到JTextFeild并且选择取消选择。

这是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();
    }
}

2 个答案:

答案 0 :(得分:3)

选择有效。但是,只有当前具有焦点的文本组件才会显示选择。

您需要做的就是按Tab键,焦点将转到文本窗格,您将看到选择。

或者您可以在setVisible(true)声明之后添加以下内容。

    pane.requestFocusInWindow();

确保在EDT上创建GUI:

EventQueue.invokeLater(new Runnable()
{
    public void run()
    {
         new SSCCE3();
    }
));

答案 1 :(得分:1)

另一种解决方案,而不是requestFocusInWindow,就像这样的荧光笔:

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