- Is it considered good practice to use two multiple frames? NO
- Are there alternatives to using two frames? Yes
- What are the alternatives? CardLayout, modal JDialog, among others
- Will I still help you solve this query? Sure, why not?
Have an instance of the second frame in the first frame. Pass the information to the second JFrame
constructor. It's that simple.
public class Frame1 extends JFrame {
String text1;
String text2;
Frame2 frame2; <--- second frame
....
public void actionPerformed(ActionEvent e) {
text1 = textField1.getText();
text2 = textField2.getText();
frame2 = new Frame2(text1, text2);
}
}
public class Frame2 extends JFrame {
String text1;
String text2;
public Frame2(String text1, String text2){
this.text1 = text1;
this.text2 = text2;
}
}
When the second frame is instantiated in the actionPerformed
, It will make the second frame appear. It is also being passed the information from the text fields. You may also want to dispose of the first frame.
A modal JDialog
is just as easy to make as a JFrame
it's the same structure. Only difference is you can set it up to be modal (meaning nothing else that it not the JDialog) can be accessed. See this answer to see hoe to set up a JDialog
for a login
Here's a very simple program using a JDialog
with your requirements
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JDialogDemo {
MyDialog dialog;
JLabel label;
JFrame frame;
public JDialogDemo() {
label = new JLabel(" ");
frame = new JFrame("Hello World");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
dialog = new MyDialog(frame, true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new JDialogDemo();
}
});
}
class MyDialog extends JDialog {
private JButton button = new JButton("Submit");
private JTextField jtf1;
private JTextField jtf2;
public MyDialog(final Frame frame, boolean modal) {
super(frame, true);
jtf1 = new JTextField(15);
jtf2 = new JTextField(15);
add(button, BorderLayout.SOUTH);
add(jtf1, BorderLayout.CENTER);
add(jtf2, BorderLayout.NORTH);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String text1 = jtf1.getText();
String text2 = jtf2.getText();
label.setText(text1 + " " + text2);
dispose();
frame.revalidate();
frame.repaint();
frame.setVisible(true);
}
});
pack();
setVisible(true);
}
}
}
It should be fairly easy to follow. Let me know if you have any questions about it