'Blocking' calls like dialog forms in .NET
Hey,
I need to show a 'level select' window in my game, and it's only purpose is to select a level from a list of available levels, and return the filename of that level.
In .NET, I would have made a dialog form, display it with ShowDialog such that the calling code would halt until the form returned, and then used a property to communicate which level was selected. For example, in C# this could look like
csharp Code:
string levelPath = String.Empty;
frmLevelSelect f = new frmLevelSelect();
if (f.ShowDialog() == DialogResult.OK)
{
levelPath = f.SelectedLevel;
}
if (levelPath != String.Empty)
{
// ... load level
}
The ShowDialog call waits until the DialogResult has been set in the frmLevelSelect form, so we can be sure that, if the user pressed OK, he has actually selected a level.
If I try the same in java, replacing ShowDialog with setVisible(true), then it does not block, but it returns immediately, and obviously the user has had no chance to select a level yet.
How can I do this? Or is there no built-in mechanism for this and should I use threads?
Re: 'Blocking' calls like dialog forms in .NET
Use the JDialog. it works the same. Just make sure this JDialog is a modal
Code:
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Test extends JFrame
{
private static final long serialVersionUID = 1L;
private final JButton button;
public Test()
{
super("Test");
button = new JButton("Click");
button.addActionListener(new ActionListener()
{
public void actionPerformed(final ActionEvent e)
{
new TestDialog(Test.this);
JOptionPane.showMessageDialog(Test.this, "Hello World!");
}
});
this.add(button);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(final String[] args)
{
new Test().setVisible(true);
}
}
class TestDialog extends JDialog
{
private static final long serialVersionUID = 1L;
public TestDialog(final Frame owner)
{
super(owner, true);
this.add(new JTextField("Hello World!"));
setLocationRelativeTo(owner);
pack();
setVisible(true);
}
}
Re: 'Blocking' calls like dialog forms in .NET
Cool, didn't know that. Let me try it out.