问题
I have two JFrames jFrame1 and jFrame2,in jFrame1 there's a textfield and a button,while clicking on button jFrame2 will appear. In jFrame2 there's also a textfield and a button.I will type a name in textfield of jFrame2 and by clicking the button in it that textfield value should appear on textfield of jFrame1. But I am not getting the focus transferred to jFrame1,i tried the code,
in 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);
}
in jFrame2,
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jFrame1 abc1=new jFrame1();
// abc1.transferFocus(); //not working
abc1.inserting(jTextField1.getText());
this.dispose();
}
I am getting value to the method inserting(),but it's not getting set into the textfield. If I again give setVisible(true) for jFrame1 it works,but I dont want to do i in that way. Is there any other way to resolve this?
回答1:
To bring focus to the field, you should use requestFocusInWindow, however I don't think that will bring the window in question back into focus.
You could use a WindowListener to monitor changes that you could respond.
For example, in jFrame1's actionPerformed handler you could
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 is requesting the text from jFrame2 cause jFrame2 doesn't know about jFrame1, there's no reference to it.
In jFrame2 you would need to add a WindowListener to handle the request for focus of the text field
addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent we) {
jTextField1.requestFocus();
}
});
回答2:
If you're using your second frame to just take a user's input, why not switch to using a JOptionPane.showInputDialog()? You can configure this to give you a TextField and a Button and returns a String? Use this value to set the value of the JTextField in your first frame.
So your first method would be something like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String inputString = JOptionPane.showInputDialog(this, "Enter Value: ");
jTextField1.setText(inputString);
}
I think this one would be a simpler solution instead of working with a couple of frames and switching focus in between them.
This tutorial about "Getting the User's Input from a Dialog" might help you get a better picture about using Input Dialog.
来源:https://stackoverflow.com/questions/11982650/transferring-focus-from-new-jframe-to-previous-jframe