I'm learning about threads and I've got a problem with it. I'm trying to make 2 frames, one is a main frame and another will be shown later after clicking on a button. I want to stop the main frame while the new frame is running. Can you guys help me with a very simple example for this? (And the new frame will be closed after clicking on a button too). Just 2 frames with a button on each are enough. Much appreciated!
Asked
Active
Viewed 1,699 times
0
-
1You have to [learn about Swing](http://docs.oracle.com/javase/tutorial/uiswing/). Especially the part about [dialogs](http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html). – Seelenvirtuose Nov 22 '15 at 10:10
-
I know about dialogs but I'm asking for my Alarm application – NerdyGuy Nov 22 '15 at 10:13
-
And what problem do you have? Are you really expecting pepole to write code for you? Such questions are completely off-topic on SO! – Seelenvirtuose Nov 22 '15 at 10:15
-
Yes I am expecting people to help me, that's what SO is all about right? I can't really describe my problems and my code is just too long, too ugly to read so I'm asking for a little example, that's all. – NerdyGuy Nov 22 '15 at 10:18
-
*"Yes I am expecting people to help me, that's what SO is all about right?"* Wrong! SO is a Q&A site, where what you seek seems more a tutor or help desk. – Andrew Thompson Nov 22 '15 at 10:52
-
*"I want to stop the main frame while the new frame is running"* - Dialog. Also, remember, Swing is single threaded and not thread safe, all updates to the UI MUST be made from within the context of the EDT – MadProgrammer Nov 22 '15 at 11:00
1 Answers
5
You should avoid the use of multiple JFrame
s, use modal dialogs instead. JOptionPane
offers a ton of good, easy & flexible methods to do so.
Here's an example. When you click the button the dialog will appear on top of the JFrame
. The main JFrame
won't be clickable anymore, since JOptionPane.showMessageDialog()
produces a modal window.
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Example {
public Example() {
JFrame frame = new JFrame();
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(frame, "I'm a dialog!");
}
});
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Example();
}
});
}
}
Output:

Community
- 1
- 1

Lukas Rotter
- 4,158
- 1
- 15
- 35