JTextField.select()在动作监听器中不起作用

时间:2019-02-04 13:21:31

标签: java swing event-handling jframe

我正在尝试创建一个程序,该程序将使用JTextField中的字符串搜索JTextArea中编写的文本,并在按下“查找”按钮后选择文本。我的问题是JTextArea.select()方法在我的代码中似乎不起作用。当我按下按钮时,动作监听器正在触发,但是select()似乎什么都没做。当我在构造函数中使用它时,它可以正常工作。 (如果需要的话,我正在使用Eclipse Photon)。

这是代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JFrame implements ActionListener
{
    private JButton jbFind = null;
    private JTextField jtIpt = null;
    private JTextArea jtTex = null;

public Test()
{
    super("Find");
    setSize(400,500);

    JPanel jpSou = new JPanel(new BorderLayout());
    JPanel jpBut = new JPanel(new FlowLayout());
    JPanel jpInp = new JPanel(new FlowLayout());

    jtTex = new JTextArea("Paul said, John’s baptism was a baptism of repentance. He told the people to believe in the one coming after him, that is, in Jesus.");
        jtTex.setLineWrap(true);
    JScrollPane jsScroll = new JScrollPane(jtTex);

    jtIpt = new JTextField(20);
    JLabel jlTxt = new JLabel("Find:");

    jbFind = new JButton("Find");
    JButton jbClear = new JButton("Clear");

    jpBut.add(jbFind);
    jpBut.add(jbClear);

    jpInp.add(jlTxt);
    jpInp.add(jtIpt);

    jpSou.add(jpBut, BorderLayout.SOUTH);
    jpSou.add(jpInp, BorderLayout.NORTH);

    add(jpSou, BorderLayout.SOUTH);
    add(jtTex, BorderLayout.CENTER);

    FindHandle evt = new FindHandle();

    jbFind.addActionListener(evt);

    //jtTex.select(7, 15);
}
class FindHandle implements ActionListener
{           
    public void actionPerformed(ActionEvent ae)
    {       
        String inStr = jtIpt.getText();
        String searchStr = jtTex.getText();
        int foundLoc = searchStr.indexOf(inStr);            
        int endLoc = inStr.length() + foundLoc;

        jtTex.select(foundLoc,endLoc); 
        //jtTex.setSelectedTextColor(Color.RED);
    }    
} 

public static void main(String[] args) 
{
    Test frm = new Test();
    frm.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frm.setVisible(true);
}

public void actionPerformed(ActionEvent e) 
{

}

}

0 个答案:

没有答案