我有两个JFrames jFrame1jFrame2,在jFrame1中有一个文本字段和一个按钮,单击按钮jFrame2将会出现。在jFrame2中还有一个文本字段和一个按钮。我将在jFrame2的文本字段中键入一个名称,然后通过单击其中的按钮将文本字段值显示在jFrame1的文本字段上。但是我没有把焦点转移到jFrame1上,我尝试了代码,

在jFrame1中

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        jFrame2 abc=new jFrame2();
        abc.setVisible(true);
    }


public void inserting(String name){
   jTextField1.requestFocusInWindow();
   jTextField1.setText(name);

 }


在jFrame2中,

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

        jFrame1 abc1=new jFrame1();
       // abc1.transferFocus();  //not working

        abc1.inserting(jTextField1.getText());
        this.dispose();
    }


我对方法inserting()有所了解,但未在文本字段中设置它。如果我再次为jFrame1提供setVisible(true),它可以工作,但是我不想那样做。还有其他解决方法吗?

最佳答案

要使焦点集中在该字段上,您应该使用requestFocusInWindow,但是我认为这不会使有问题的窗口重新成为焦点。

您可以使用WindowListener监视可以响应的更改。

例如,在jFrame1actionPerformed处理程序中,您可以

Frame02 frame2 = new Frame02();
frame2.addWindowListener(new WindowAdapter() {

    @Override
    public void windowClosed(WindowEvent we) {

        Frame02 frame2 = (Frame02) we.getWindow();
        jTextField1.setText(frame2.getText());

        toFront();
        jTextField1.requestFocusInWindow();

    }

});

frame2.setVisible(true);
frame2.toFront();
frame2.requestFocus();


jFrame1正在从jFrame2请求文本,因为jFrame2不知道jFrame1,对此没有引用。

jFrame2中,您需要添加WindowListener来处理文本字段的焦点请求

addWindowListener(new WindowAdapter() {
    public void windowOpened(WindowEvent we) {
        jTextField1.requestFocus();
    }
});

10-08 01:27