Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
       }
     }
  });
}
like image 678
Harry Joy Avatar asked Feb 02 '11 12:02

Harry Joy


2 Answers

Don't make the frame visible in the ClassTwo constructor. Instead, keep a reference to classTwo in classOne, and when the button is clicked, make it visible, like so:

//on button click
if(classTwo == null){
    classTwo = new ClassTwo();
}
classTwo.setVisible(true);

Also change classTwo's default close operation to hide on close, instead of exit:

setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

So it doesn't matter how many times the button is clicked, because all it does is make the existing instance visible. It doesn't create new instances.

like image 134
dogbane Avatar answered Oct 22 '22 12:10

dogbane


In ClassOne you could simply remember whether you opened a new ClassTwo using a boolean.

//in event handler for the button
if (!classTwoShown)
{
  classTwoShown = true;
  new ClassTwo();
}

You should also hook into the dispose event of class two to reset the classTwoShown flag.

like image 41
Qwerky Avatar answered Oct 22 '22 14:10

Qwerky