Reputation: 25
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
Upvotes: 0
Views: 2946
Reputation: 13057
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;
}
}
}
}
Upvotes: 2