Reputation: 25
I made a simple JDialog which contains a label and a button, its basically an equivalent of information dialog. So in the dialog, there is a method display() in which I called setVisible(true) five times.
From my knowledge, when this display method is called it should only display the dialog once but it actually created 5 dialogs, Why did it create 5 dialogs?
Edit1: My problem is more similar to this :
import java.awt.event.*;import java.awt.*;import javax.swing.*;
class Demo implements ActionListener
{
JFrame f;
JButton b;
DisplayDialog dialog;
public Demo()
{
f = new JFrame();
f.setSize(200,200);
b = new JButton("Click me");
f.add(b);
dialog = new DisplayDialog();
b.addActionListener(this);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Object o = e.getSource();
if(o==b)
{
dialog.display("Hello");
dialog.display("Hello");
dialog.display("Hello");
dialog.display("Hello");
dialog.display("Hello5");
}
}
public static void main(String args[])
{
Demo d = new Demo();
}
class DisplayDialog implements ActionListener
{
JDialog dg;
JLabel l;
JButton b;
Font myfont;
public DisplayDialog()
{
dg = new JDialog(f,"Alert!",true);
dg.setSize(300,150);
l = new JLabel("Message");
b = new JButton("OK");
myfont = new Font("Serif",Font.BOLD,12);
l.setFont(myfont);
dg.add(l);
dg.add(b,"South");
dg.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object o = e.getSource();
if(o==b)
{
dg.setVisible(false);
}
}
public void display(String str)
{
l.setText(str);
dg.setVisible(true);
}
}
}
Edit2 : Now a situation like this is occurring in my program and rather than displaying the dialog 5 times, I want it to display the last one, what can i do to achieve this?
Upvotes: 2
Views: 24673
Reputation: 32507
As to your edit: What is your problem then?
Change
if (o == b) {
dialog.display("Hello");
dialog.display("Hello");
dialog.display("Hello");
dialog.display("Hello");
dialog.display("Hello5");
}
to
if (o == b) {
dialog.display("Hello");
}
Upvotes: 0
Reputation: 83527
You only create one dialog instance with
dg = new JDialog(f,"Alert!",true);
Then you display this same dialog five times with the multiple calls to setVisible(true)
.
Upvotes: 0
Reputation: 32507
Ok so basicly it is not showing 5 times at once only it is shown 5 times in a row.
JDialog.setVisible(true)
is a blocking operation and blocks until dialog is closed.
So one dialog pops up and app blocks on setVisible(true)
when you close it, another serVisible(true)
is invoked and so on.
Upvotes: 4