Search code examples
javaswingwindowsmack

how to stop opening of duplicate window using Smack API in swing?


I have 2 swing classes which extends JFrame. Both have show() method in there constructor. From ClassOne i called ClassTwo like new ClassTwo() on button click event. But if i press the button again new window for ClassTwo is opened. So how can i stop opening of ClassTwo window if one ClassTwo window is opened ?

Edit

now this problem is solved but now when i first open ClassTwo window it shows one window. Then after closing it when i again open ClassTwo window it opens two window and this count keep on increamenting. Why this is happening?

EDIT 2

I found that its not swing problem but its problem from MultiUsreChat class of Samck API. So anyone who have worked on it help me.

the code in ClassOne is:

if(!winList.contains(room_jid)){
    new ClassTwo(room_jid,....);
    winList.add(room_jid);
}

and in ClassTwo is:

public ClassTwo(....){
......
    this.muc = new MultiUserChat(connection, room_jid);
    if(!muc.isJoined())
        muc.join(this.user_id);      //---- This line opens previously closed window.
.....

    if(!isVisible())
       show();

}

Edit 3

constructor of classone

public ClassOne(){
  JButton btn = new JButton("Open");
  btn.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent e){
       if(!winList.contains(room_jid)){
           new ClassTwo(room_jid,....);
            winList.add(room_jid);
       }
     }
  });
}

Solution

  • The reason it does not work is that you are creating a new instance of ClassTwo inside the button handler, which means you create a new window every time the button is pressed. This should work:

    private Map<JButton, ClassTwo> classTwoMap;
    
    public ClassOne(){
      classTwoMap = new HashMap<JButton, ClassTwo>();
      ClassTwo bn1window = new ClassTwo();
      bn1window .setVisible(false);
      //initialisation code for your window
      .....
      JButton btn = new JButton("Open");
      btn.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
            classTwoMap.Get(e.getSource()).setVisible(true);
         }
      });
    
      classTwoMap.Get(btn).setvisible(false);
    }
    
    //Edit:
    public ClassTwo() {
        // This will hide the window when closed, and the button will re-"open" it.
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    }
    

    You can use any combination of the other answers inside the button handler, such as toggle functionality or other complex ideas, such as a singleton. But the main thing is that you should note create a new window in the button handler, but create it somewhere where it only gets called exactly once.

    Edited for multiple windows and buttons.