2

I am coding MVC. In my controller i am listening to the action and if the user clicks a "SHOW-LIST" button i am making an instance of my view class which extends from JFrame and therein the view class i create a new JFrame. My problem is that if i click on SHOW-LIST button multiple times, i have the frame opened multiple time. Can somebody please tell me how can i do so so that once a new frame is about to open the old frame closes..

Controller

public void actionPerformed(ActionEvent event) {
  String viewAction = event.getActionCommand();
  ...
    if (viewAction.equals("SHOW-LIST")) {
      showListUI = new ShowListDialogUI(displayedCustomerList);
    }
}

View

class ShowListDialogUI extends JFrame{
  public ShowListDialogUI (List<Customer> customerList) {
    ..
    // I am drawing it here
    ..
  }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
mu_sa
  • 2,685
  • 10
  • 39
  • 58
  • 2
    See also [*The Use of Multiple JFrames, Good/Bad Practice?*](http://stackoverflow.com/q/9554636/230513) – trashgod Oct 25 '12 at 16:06

2 Answers2

3

Can somebody please tell me how can i do so so that once a new frame is about to open the old frame closes..

  • use CardLayout, then there no reason to playing with Top-Level Containers, put there required number of JPanels, then just to switch betweens JPanel views

  • as @trashgod notified, really not good idea, way

  • otherwise have to clean-up (remove all contents) uselless container, because Top-Level Containers never will be GC'ed

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

Well, depends on the use case, but instead of closing the old one, and creating the new one, you could focus the existing one (and probably update data?).

Your controller can manage the frames and keep track of it. In the most easiest (and not recommended) way, you have a boolean "isFrameOpen". You set it to true if you open the frame, to false if you close it (your frame has to communicate with the controller then, or the controller has to know about the status of the frame at least). If boolean is true, then focus/recreate it. If false, create a new one.

In more advanced solutions, you can keep track over all frames with a map and you have to deal carefully with concurrent access.

--tb

tb-
  • 1,240
  • 7
  • 10
  • The idea presented by you is good, though why to use a boolean variable, when `JFrame` itself gets this method from `Window` Class, called [isShowing()](http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#isShowing()). +1 for the idea, but not the technique that you applied :-) – nIcE cOw Oct 25 '12 at 17:12
  • @GagandeepBali I totally agree, that is the reason I wrote "(and not recommended)" :) It was meant to be easily understandable. – tb- Oct 25 '12 at 18:34