I have a button in a JFrame, if pressed, it takes us to another frame. I used this code:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt
you shouldn't use more then one frame.
You should have NOTHING in JFrame except defaultExitOperation, size, preferedsize and visible true. Instead place all buttons and fields into a JPanel and add/remove the JPanel from the JFrame.
If you want another Window open use JDialog.
btw: you can have your MainFrame setVisible false and open a JDialog with your MainFrame as parent. Only if someone writes down the right user + password you make the MainFrame visible.
If you pass your MainForm
to the SecondForm
class (for example using a constructor parameter) the SecondForm
instance can make the original MainForm
instance visible again instead of creating a new one.
For example
public class SecondForm extends JFrame{
private final MainForm mainForm;
public SecondForm( MainForm form ){
mainForm = form;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
mainForm.setVisible(true);
setVisible(false);
dispose();
}
}
and in your MainForm
class
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
SecondForm secondform = new SecondForm( this );
secondform.setVisible(true);
setVisible(false);
dispose();
}
For swing applications, the standard is to use a STATIC MAIN FRAME, in other words, make your main frame (mframe) static and add methods to pop-up new frames, dialogs, optionPanes, etc. You can even control the visibility of the main frame throw static calls. That's the way you implement a UNIQUE FRAME for your application, even tho you instance other frames for navigation, all child frames can refer to the main frame without the need of passing it as parameter to constructors or creating new instances of it.
`/* to start the application */
public class Main{
public static MainFrame MFRAME;
public static void main(String[] args){
/*use this for thread safe*/
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Main.MFRAME = new MainFrame(/*init parms to constructor*/);
}
});
}
}
`
`/* to create the main frame */
public class MainFrame extends JFrame{
public MainFrame(/*your constructor parms*/){
/* constructor implementation */
}
public void openOtherFrame(/*your parms*/){
OtherFrame oFrm = new OtherFrame(/*your parms*/);
}
/* other methods implementation */
}
`
`/* to open child frames controling the visibility of the main frame*/
public class OtherFrame extends JFrame{
public OtherFrame(/*your constructor parms*/){
/* hide main frame and show this one*/
Main.MFRAME.setVisible(false);
this.setVilible(true);
/* do something else */
/* show main frame and dispose this one*/
Main.MFRAME.setVisible(true);
this.dispose();
}
/* other methods implementation */
}
`