I have a problem with the dispose method. . .I got 3 java files with a class name:

MainProgram.java
MainPanel.java
PageOne.java

The MainProgram java extends JFrame.
The MainPanel.java extends JPanel.
The PageOne.java extends JFrame.

The MainPanel.java is where all the actions and etc. are being set.
The MainProgram.java calls the MainPanel.java to display what is in the MainPanel.java.
All of these works good until I put the dispose(); method on one of the condition. All I want is to close the MainProgram.java before calling or opening the PageOne.java. I thought the use of method dispose(); would be same as using it in JFrame. Can you give a good idea on how to do this? I am using mouseListener on my action.

When I want to go from one frame to another I use:

JFrame.setVisible(true/false);

If you call it with false, the frame is not lost. It is just not visible. Meaning that you can call back the same method and set it to visible(true) whenever you want and the frame will reappear

use this
MainProgram mp = new MainProgram();
mp.setVisible(false);

This way you can hide the MainProgram JFrame. Don't think of disposing it. This is another alternative.

Regards

Sincerelibran

I have a problem with the dispose method. . .I got 3 java files with a class name:

MainProgram.java
MainPanel.java
PageOne.java

The MainProgram java extends JFrame.
The MainPanel.java extends JPanel.
The PageOne.java extends JFrame.

The MainPanel.java is where all the actions and etc. are being set.
The MainProgram.java calls the MainPanel.java to display what is in the MainPanel.java.
All of these works good until I put the dispose(); method on one of the condition. All I want is to close the MainProgram.java before calling or opening the PageOne.java. I thought the use of method dispose(); would be same as using it in JFrame. Can you give a good idea on how to do this? I am using mouseListener on my action.

I use the setVisible method, still it won't work. . .try to look at the code below:

import javax.swing.*;
import java.awt.*;
import java.util.*;

public class MainPage extends JFrame {
	private MainPagePanel mpp;

	public MainPage() {
		super("Test");
		setSize(180,100);
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		mpp = new MainPagePanel();
		Container pane = getContentPane();
		pane.add(mpp);
		setContentPane(mpp);
		setResizable(false);
		setVisible(true);
	}

	public static void main(String[] args) {

		MainPage mp = new MainPage();
	}
}
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;

public class MainPagePanel extends JPanel {

	ImageIcon image;
	JLabel display;

	public MainPagePanel() {
		Toolkit kit = Toolkit.getDefaultToolkit();

		image = new ImageIcon("menu1.jpg");
		display = new MapLabel(image, "Display");
        display.setBounds(10, 20, image.getIconWidth(), image.getIconHeight());

        setPreferredSize(new Dimension(457, 540));
        setLayout(null);
        add(display);

	}

	class MapLabel extends JLabel implements MouseListener {
		Icon icon;
        String name;
        MainPage mp; // Declaring MainPage mp = new MainPage(); here will result to error

        public MapLabel(Icon icon, String name) {
		    this.icon = icon;
		    this.name = name;

		    setIcon(icon);
		    setToolTipText(name);
            addMouseListener(this);
		}

   	public void mouseClicked(MouseEvent e) {
		String image = name;

		if(image.equals("Display")) {
			// How can I close the MainPage program if I click the display image label before PageOne will appear?
			// setVisibility won't work.
			PageOne po = new PageOne();
			mp.setVisible(false); // disposing PageOne
			mp.dispose(); //disposing PageOne
			mp = new MainPage();
        }

	}
	public void mouseEntered(MouseEvent e) {
            setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }
    public void mouseExited(MouseEvent e) {
            setCursor(null);
    }
    public void mousePressed(MouseEvent e) {}
	public void mouseReleased(MouseEvent e) {}
	}
}

I have a problem in the if condition and also in declaring the MainPage mp = new MainPage();

Here is the whole to program to test. . .

this instruction is ambigous: addMouseListener(this); it's similar to this.addMouseListener(this);

From what I see you use a lot of "extending" that I don't think is necessary. Your code works but it could have been simpler.
First don't use the "dispose" method.

Second you need to close the the MainPage and open the PageOne.
To do that you need to call the setVisible(false) on the MainPage that is open. In order to have access to the original MainPage that you opened you need to pass it as parameter to the MapLabel.
But MapLabel is called from the MainPagePanel so that also needs to have it as parameter:

MapLabel class

MainPage mp; 

public MapLabel(Icon icon, String name, MainPage mp) {

   this.mp = mp;
}

// AT THE LISTENER:

......
PageOne po = new PageOne();
mp.setVisible(false); // disposing PageOne

// [B]mp = new MainPage();[/B] // you don't need that. It will create a new MainPage and overwrite the existing one.
// you have already created a MainPage, don't create another

But in order to call this: public MapLabel(Icon icon, String name, MainPage mp) you need:

MainPagePanel class

MainPage mp;

public MainPagePanel(MainPage mp) {
		Toolkit kit = Toolkit.getDefaultToolkit();

		image = new ImageIcon("menu1.jpg");
                this.mp = mp;
display = new MapLabel(image, "Display", mp);

And now to pass the MainPage that is opened as paramater

MainPage class

public MainPage() {
		super("Test");
		setSize(180,100);
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

// "this" is a MainPage. This MainPage that you just created and has all your Panels and labels
		mpp = new MainPagePanel([B]this[/B]);

		Container pane = getContentPane();
		pane.add(mpp);
		setContentPane(mpp);
		setResizable(false);
		setVisible(true);
	}

With that way, "this", is in all the other Panels and Labels and they have access to the same MainPage that you just opened.
Now that you have it inside you can pass it to the PageOne class and after you are done the PageOne can set it back to visible true while setting itself to false:

class PageOne

class PageOne {
  MainPage mp;

public PageOne(MainPage mp) {
 this.mp = mp;
}

....
...
// in some method:
{
   this.setVisble(false); //hiding PageOne
   mp.setVisible(true);
}
}

It is better to call dispose on the PageOne:

mp.setVisible(true);
this.dispose();

Because you created it locally inside the Label and no one else has access to it, so if it is disposed no one will be affected by it.
Also whenever you call "Display" you create a new one, so if you set it to visible false, you will keep creating new PageOne objects that afterward will be simply not visible.
If you had it as a private property of the class and you simply changed its values (not create a new one) thetn it would be OK

commented: good job, your idea work well +0

this instruction is ambigous: addMouseListener(this); it's similar to this.addMouseListener(this);

What do you mean by that? Do you think it is wrong?

the implicite variable "this" is called even if it is omited:
so writing addMouseListener(this); issimilar to it's similar to this.addMouseListener(this);

the implicite variable "this" is called even if it is omited:
so writing addMouseListener(this); issimilar to it's similar to this.addMouseListener(this);

I didn't understood you correctly, I thought you said this was an error

What do you mean by that? Do you think it is wrong?

No, there's nothing wrong with it all. It's definitely not ambiguous!

addMouseListener(this);

calls the addMouseListener method on the current object - the thing called "this".

this.addMouseListener(this);

just makes that fact explicit, but the first "this" is unnecessary.

People don't normally code the "this" in this.someMethod, but there are times when you may want to do that to draw a reader's attention to what you are doing.

But writing the instruction:
addMouseListener(this);
in the inner class MapLabel means that the implicite (ommited optional"this") point to the same variable "this" the parammetre of the method addMousListner.

But writing the instruction:
addMouseListener(this);
in the inner class MapLabel means that the implicite (ommited optional"this") point to the same variable "this" the parammetre of the method addMousListner.

Yes, but so what? I don't understand what point you are trying to make.

it is not a question of if the "this" is necessary or not, but the instruction on it self use a variable as an instance of a class and it use the same variable as argument.
But the programmer in his mind that the firt (implicit "this") point to an instance of the MainPagePanel not to the inner class MapLabel .

...But the programmer in his mind that the firt (implicit "this") point to an instance of the MainPagePanel not to the inner class MapLabel .

Ah, OK, now I see the point you are making. Thanks

Thank you so much javaAddict, your idea did worked . . .

//ToolbarFrame2.java
// The Swing-ified button example.
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ToolbarFrame2 extends Frame implements ActionListener
 {
// This time, let's use JButtons!
JButton cutButton, copyButton, pasteButton;
JButton winButton, javaButton, motifButton;
    public ToolbarFrame2() 
    {
    super("Toolbar Example (Swing)");
    setSize(450, 250);
    addWindowListener(new BasicWindowMonitor());
    // JPanel works similarly to Panel, so we'll use it
    JPanel toolbar = new JPanel();
    toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));
    cutButton = new JButton("Cut");
    cutButton.addActionListener(this);
    toolbar.add(cutButton);
    copyButton = new JButton("Copy");
    copyButton.addActionListener(this);
    toolbar.add(copyButton);
    pasteButton = new JButton("Paste");
    pasteButton.addActionListener(this);
    toolbar.add(pasteButton);
    add(toolbar, BorderLayout.NORTH); // the new BorderLayout add
    // Add the look-and-feel controls
    JPanel lnfPanel = new JPanel();
    LnFListener lnfListener = new LnFListener(this);
    javaButton = new JButton("Metal");
    javaButton.addActionListener(lnfListener);
    lnfPanel.add(javaButton);
    motifButton = new JButton("Motif");
    motifButton.addActionListener(lnfListener);
    lnfPanel.add(motifButton);
    winButton = new JButton("Windows");
    winButton.addActionListener(lnfListener);
    lnfPanel.add(winButton);
    add(lnfPanel, BorderLayout.SOUTH);
    }
public void actionPerformed(ActionEvent ae) {
System.out.println(ae.getActionCommand());
}
public static void main(String args[]) 
    {
    ToolbarFrame2 tf2 = new ToolbarFrame2();
    tf2.setVisible(true);
    }
}

public class LnFListener implements ActionListener {
Frame frame;
public LnFListener(Frame f) {
frame = f;
}
public void actionPerformed(ActionEvent e) {
String lnfName = null;
if (e.getActionCommand().equals("Metal")) {
lnfName = "javax.swing.plaf.metal.MetalLookAndFeel";
} else if (e.getActionCommand().equals("Motif")) {
lnfName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
} else {
lnfName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
}
try {
UIManager.setLookAndFeel(lnfName);
SwingUtilities.updateComponentTreeUI(frame);
}
catch (UnsupportedLookAndFeelException ex1) {
System.err.println("Unsupported LookAndFeel: " + lnfName);
}
catch (ClassNotFoundException ex2) {
System.err.println("LookAndFeel class not found: " + lnfName);
}
catch (InstantiationException ex3) {
System.err.println("Could not load LookAndFeel: " + lnfName);
}
catch (IllegalAccessException ex4) {
System.err.println("Cannot use LookAndFeel: " + lnfName);
}
}
}
commented: And what is this suppose to be? -1
commented: oh dear. +0

Hello all,
Sorry to necro this thread, but I'm in need of a bit of help, and I was trying to implement what was written here to my scenario... but I still cannot figure it out.
My scenario is slightly different that what the OP has presented. So here goes:
Simple java app. I have Jframe1 and Jframe2. On JFrame1 I have a checkbox that will open Jframe2.
I can get this part with no problems. However, I'm trying to figure out how to make JFrame2 hide or dispose when the checkbox is deselected/unchecked.
I've tried various methods with the setVisible(true/false) and even fumbled about with an if/else statement trying to see if I could get it working. It's not working. Basically if I uncheck the box, it will create yet another JFrame2 instead of destroying the first one when the checkbox was originally selected.

I think I'm on the right path with the code, but perhaps my implementation is a bit off?

import java.awt.event.ItemEvent;
public class MainMenu extends javax.swing.JFrame {

    /** Creates new form MainMenu */
    public MainMenu() {
        initComponents();
    }
                          
   private void initComponents() {

      jCheckBox1 = new javax.swing.JCheckBox();
      DataDetectionChkBtn = new javax.swing.JCheckBox();
      ChkBox3 = new javax.swing.JCheckBox();
      jCheckBox4 = new javax.swing.JCheckBox();
      jToggleButton1 = new javax.swing.JToggleButton();
      jMenuBar1 = new javax.swing.JMenuBar();
      FileMenu = new javax.swing.JMenu();
      openFile = new javax.swing.JMenuItem();
      closeFile = new javax.swing.JMenuItem();
      saveFile = new javax.swing.JMenuItem();
      exitMenu = new javax.swing.JMenuItem();
      EditMenu = new javax.swing.JMenu();
      OptionsMenu = new javax.swing.JMenu();
      HelpMenu = new javax.swing.JMenu();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      setTitle("Mobile Data Center");
      setResizable(false);

      jCheckBox1.setFont(new java.awt.Font("DejaVu Sans", 1, 14));
      jCheckBox1.setText("Data Manipulation");
      jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            showNewJFrame(evt);
         }
      });

      DataDetectionChkBtn.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N
      DataDetectionChkBtn.setText("Data Detection");
      DataDetectionChkBtn.addItemListener(new java.awt.event.ItemListener() {
         public void itemStateChanged(java.awt.event.ItemEvent evt) {
            DataDetectionChkBox(evt);
         }
      });

      ChkBox3.setFont(new java.awt.Font("DejaVu Sans", 1, 14));
      ChkBox3.setText("Data Capture");
      ChkBox3.addItemListener(new java.awt.event.ItemListener() {
         public void itemStateChanged(java.awt.event.ItemEvent evt) {
            DataCapture(evt);
         }
      });

      jCheckBox4.setFont(new java.awt.Font("DejaVu Sans", 1, 14));
      jCheckBox4.setText("Data Portview");

      jToggleButton1.setText("TestToggle");

      FileMenu.setText("File");

      openFile.setText("Open");
      FileMenu.add(openFile);

      closeFile.setText("Close");
      FileMenu.add(closeFile);

      saveFile.setText("Save");
      FileMenu.add(saveFile);

      exitMenu.setText("Exit");
      exitMenu.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            exitMenuActionPerformed(evt);
         }
      });
      FileMenu.add(exitMenu);

      jMenuBar1.add(FileMenu);

      EditMenu.setText("Edit");
      jMenuBar1.add(EditMenu);

      OptionsMenu.setText("Options");
      jMenuBar1.add(OptionsMenu);

      HelpMenu.setText("Help");
      jMenuBar1.add(HelpMenu);

      setJMenuBar(jMenuBar1);

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addGap(38, 38, 38)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addComponent(jToggleButton1)
               .addComponent(jCheckBox4)
               .addComponent(DataDetectionChkBtn)
               .addComponent(jCheckBox1)
               .addComponent(ChkBox3))
            .addContainerGap(44, Short.MAX_VALUE))
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addGap(35, 35, 35)
            .addComponent(jCheckBox1)
            .addGap(18, 18, 18)
            .addComponent(DataDetectionChkBtn)
            .addGap(18, 18, 18)
            .addComponent(ChkBox3)
            .addGap(18, 18, 18)
            .addComponent(jCheckBox4)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jToggleButton1)
            .addContainerGap(17, Short.MAX_VALUE))
      );

      layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {ChkBox3, DataDetectionChkBtn, jCheckBox1, jCheckBox4});

      pack();
   }

    private void exitMenuActionPerformed(java.awt.event.ActionEvent evt) {       
       System.exit(1);
    }                                        

    private void showNewJFrame(java.awt.event.ActionEvent evt) {  
       new DataManipulationFrame().setVisible(true);
    }                              

    private void DataDetectionChkBox(java.awt.event.ItemEvent evt) {    
       Object source = evt.getItemSelectable();
//       if (source == DataDetectionChkBtn) {
//          new DataDetectionFrame().setVisible(true);
//       } //else if (source != DataDetectionChkBtn) {
//          //new DataDetectionFrame().setVisible(false);
//       if (evt.getStateChange() == ItemEvent.DESELECTED) {
//          new DataDetectionFrame().setVisible(false);
//       }
       new DataManipulationFrame().setVisible(false);
    }                                    

    private void DataCapture(java.awt.event.ItemEvent evt) {      
       Object source = evt.getItemSelectable();
       if (source == ChkBox3) {
          new DataDetectionFrame().setVisible(true);
       } else {
          if (evt.getStateChange() == ItemEvent.DESELECTED) {
             new DataDetectionFrame().dispose();
          }
       }
    }                            

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainMenu().setVisible(true);
            }
        });
    }

   // Variables declaration - do not modify                     
   private javax.swing.JCheckBox ChkBox3;
   private javax.swing.JCheckBox DataDetectionChkBtn;
   private javax.swing.JMenu EditMenu;
   private javax.swing.JMenu FileMenu;
   private javax.swing.JMenu HelpMenu;
   private javax.swing.JMenu OptionsMenu;
   private javax.swing.JMenuItem closeFile;
   private javax.swing.JMenuItem exitMenu;
   private javax.swing.JCheckBox jCheckBox1;
   private javax.swing.JCheckBox jCheckBox4;
   private javax.swing.JMenuBar jMenuBar1;
   private javax.swing.JToggleButton jToggleButton1;
   private javax.swing.JMenuItem openFile;
   private javax.swing.JMenuItem saveFile;
   // End of variables declaration
}

As you can see, some of my attempts have been commented out. I left them in for reference so that I could go back and edit/re-try as needed.

Any help is greatly appreciated.

I haven't look at your code but from your explanation, I assume that you create the second frame, when the button is clicked?
If yes declare the second frame as global variable and create it once. In the previous way you keep creating a new one.
With this way whatever you do to the frame will be applied to the same instance:

class Frame1 extends JFrame {
  private Frame2 frame2 = new Frame2();

  // now you can set to visible false or true the frame2 whenever you want
}

I haven't look at your code but from your explanation, I assume that you create the second frame, when the button is clicked?
If yes declare the second frame as global variable and create it once. In the previous way you keep creating a new one.
With this way whatever you do to the frame will be applied to the same instance:

class Frame1 extends JFrame {
  private Frame2 frame2 = new Frame2();

  // now you can set to visible false or true the frame2 whenever you want
}

@javaAddict,
Awesome. Thanks for setting me in the right direction. I added the following code as suggested and it seems to work perfectly:

private DataDetectionFrame frame2 = new DataDetectionFrame();
    private void DataDetectionChkBox(java.awt.event.ItemEvent evt) {
       Object source = evt.getItemSelectable();
       if (DataDetectionChkBox.isSelected())
          frame2.setVisible(true);
       else
          frame2.setVisible(false);
    }

Much appreciated. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.