My question is related about java swing frame. I have a 2 jFrame. jFrame1 and jFrame2. there is a jbutton is in the jframe 1 so when user click the jbutton I want to focus to frame 2(Frame 2 is already loaded in the application.) without closing frame1. Please help to do this
Asked
Active
Viewed 2,852 times
0
-
3Use modal dialogs! Also, see this question [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice) – Branislav Lazic Aug 23 '13 at 16:05
-
Don't know that the JDialog needs to be modal, but yes you should be using a JDialog as a child Window. – camickr Aug 23 '13 at 17:06
1 Answers
2
You can use Window.toFront()
to bring the current frame to front:
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MyFrame extends JFrame implements ActionListener {
public MyFrame(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button = new JButton("Bring other MyFrame to front");
button.addActionListener(this);
add(button);
pack();
setVisible(true);
}
public static void main(String[] args) {
new MyFrame("1");
new MyFrame("2");
}
@Override
public void actionPerformed(ActionEvent e) {
for (Window window : Window.getWindows()) {
if (this != window) {
window.toFront();
return;
}
}
}
}

Moritz Petersen
- 12,902
- 3
- 38
- 45
-
This is the 'right answer to the wrong question'. See comments. – Andrew Thompson Aug 23 '13 at 17:17