I'm trying to add components to a JDialog after it has been created and displayed. Nothing I try makes the changes actually update to the screen, and I've read and applied every question I could find related to this.
This example code creates a modal JDialog showing the word "test". I cannot get it to display "test2". Almost exactly the same code but with a JFrame instead of a JDialog behaves as I expect, so I don't understand. I'm new to Java and especially to swing.
import javax.swing.*;
public class DialogTester {
public static void main(String[] args) {
new DialogTester();
}
public DialogTester() {
JFrame jframe = new JFrame();
jframe.setVisible(true);
JDialog jdialog = new JDialog(jframe,true);
JPanel jpanel = new JPanel();
jpanel.add(new JLabel("test"));
jdialog.add(jpanel);
jdialog.setVisible(true);
jpanel.add(new JLabel("test2"));
jpanel.revalidate();
jdialog.getContentPane().validate();
jdialog.pack();
}
}
I also tried calling
jdialog.repaint();
which did nothing.
You created a modal dialog. So, as soon as you call setVisible(true), the following instructions wait for the dialog to be closed to be executed.
Put the code adding a label before the dialog is made visible, or put it in an event handler called after the dialog is shown, for example, when you click on a button in this dialog.
Related
How would I go about closing a JFrame based on an ActionEvent from a button click within a JPanel?
I have a total of three classes:
Application: contains the main method and runs the program by creating a FrameStartUp object.
FrameStartUp: extends the JFrame class and displays the contents within StartUpPanel.
StartUpPanel: extends the JPanel class and has all the components and ActionEvents.
Within the StartUpPanel class, I have a button with an ActionEventListener waiting for the button to be clicked.
When the button is clicked I want the application to shut down completely. I know of a method called .dispose() for the JFrame class, but I can't use it because creating an object of FrameStartUp would just run another GUI (run by the constructor).
As I am new to programming and swing, I do not know any other way to fix this, other than getting rid of the StartUpPanel and just creating a JPanel within the FrameStartUp class.
Are there any methods provided by Swing that can access the current JFrame that the panel is on, so the program can close when the ActionEvent is triggered?
I know of a method called .dispose() for the JFrame class
This will work if you explicitly set setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Are there any methods provided by Swing that can access the current JFrame that the panel is on
Yes... SwingUtilities provides one called getWindowAncestor().
button.addActionListener(e -> {
SwingUtilities.getWindowAncestor((Component)e.getSource()).dispose();
});
... or more commonly, you can chose to reference a final variable to achieve the same effect...
final JFrame swingStuff = this; // or expose via a getter/setter
button.addActionListener(e -> {
swingStuff.dispose();
});
... however the final variable placement and setter/getter would need a small reproducible code example.
And finally, as others have mentioned, System.exit(0) works quite fantastically well too, so as long as it doesn't break the lifecycle of any of your other components.
My test class:
import javax.swing.*;
import java.awt.*;
public class SwingStuff extends JFrame {
// Our main JFrame
public SwingStuff() {
super();
// The button
JButton button = new JButton("Close");
button.addActionListener(e -> {
SwingUtilities.getWindowAncestor((Component)e.getSource()).dispose();
});
// The JPanel and nested components
JPanel startupPanel = new JPanel();
startupPanel.add(button);
add(startupPanel);
pack();
// Make sure the app exits when closed
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// Just our entry point
public static void main(String ... args) {
SwingUtilities.invokeLater(() -> {
new SwingStuff().setVisible(true);
});
}
}
I want to show a "Please wait" JFrame while my program copies some files.
Context : I have a first JFrame that allows a user to pick files and then clicks on a button to trigger the copy. This is when I want to display the "Please wait" JFrame and make it disappears when everything is done.
I have succeeded to make this JFrame appeared and disappeared but it is always blank.
The code for the "Please Wait" JFrame :
public class Loader implements Runnable {
JFrame loadingFrame = new JFrame();
#Override
public void run() {
// Parameters for size and position
loadingFrame.setSize(180,100);
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel("Please wait ...", SwingConstants.CENTER), "Center");
loadingFrame.add(panel);
loadingFrame.setLocationRelativeTo(null);
loadingFrame.setVisible(true);
//((JComponent) loadingFrame.getContentPane()).revalidate();
//loadingFrame.repaint();
}
public void destroy() {
loadingFrame.setVisible(false);
loadingFrame.dispose();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Loader());
}
}
As you can see, I tried "repaint()" and "revalidate()" but it didn't work.
I call the Loader class in this function :
public void analyzeAndCopy(){
// Show loading Frame
Loader loader = new Loader();
loader.run();
[... copy code...]
// Hide loading Frame
loader.destroy();
}
The Please Wait JFrame appears blank, and stays (as wanted) while files are being copied and disappears after, but it stays blank all the way. :/
I think it may be related to Thread, I tried to create a 2nd thread to call the JFrame, it didn't work. I'm running out of ideas...
Any help will be much appreciated ! :)
Thanks
try to replace
loader.run();
with
new Thread(loader).start();
and add a line to method run:
loadingFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
and you can use JDialog instead of JFrame
i created a dialog class that opens when a JLabel is clicked but i want the main window to close when the label is clicked and a more bigger issue is that the label is in a class that extends a JPanel now if the label is clicked the panel goes as in setVisible(false), do you get what i mean, but when i tried to use polymorphism in the panel class to obtain both the main window class and the dialog it proved successful but when the label is clicked an new similar main
wnidow pops up and immediately disappears. ie it duplicates the main window, i know that this problem might look like a chalenge because there are no codes, the file is too complicated but i kmow there is a pro out there who can get a picture of what this code is and help me, thank you
"an new similar main wnidow pops up and immediately disappears. ie it duplicates the main window, " -
Seeing how your JPanel is a separate class, it seems to me like you have a referencing issue. I bet what you did was create a new MainWindow so that you could reference it. Like
mousePressed(MouseEvent e) {
MainWindow window = new MainWindow();
window.dispose();
}
That would definitely explain the the issue. There are a few ways to deal with this. I'm going to give you the rookie way, since you still seem like a rook :D You'll probably learn more proper ways as your learning gets deeper. So you can do something like below, where you pass the reference of the MainWindow to the JPanel class, instead of creating a new MainWindow
public class MyPanel extends JPanel {
private MainWindow window;
public MyPanel(final MainWindow window) {
this.window = window;
JLabel label = new Label();
label.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
window.setVisible(false); // or dispose
}
});
}
}
When you instantiate the MyPanel, pass the reference of the MainWindow to the MyPanel, like MyPanel panel = new MyPanel(MainWindow.this);
I just created a GUI, now I want to create another GUI and link both together.
So on the first GUI when the user selects 'next' button, the second GUI is displayed.
For this, do I have to create a new class and just create a GUI again?
Here is what I have now:
import java.awt.Color;
import javax.swing.*;
public class Wizard {
private JLabel lblPicture;
private JRadioButton btLdap, btKerbegos, btSpnego, btSaml2;
private JButton btNext;
private JPanel panel;
public static void main(String[] args) {
new Wizard();
}
public Wizard() {
JFrame frame = new JFrame("Wizard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,360);
frame.setVisible(true);
MyPanel();
RadioButtons();
Button();
Image();
groupButton();
frame.add(panel);
frame.setVisible(true);
}
public void MyPanel() {
panel = new JPanel();
panel.setLayout(null);}
public void RadioButtons() {
btLdap = new JRadioButton ("Ldap");
btLdap.setBounds(60,85,100,20);
panel.add(btLdap);
btKerbegos = new JRadioButton ("Kerbegos");
btKerbegos.setBounds(60,115,100,20);
panel.add(btKerbegos);
btSpnego =new JRadioButton("Spnego");
btSpnego.setBounds(60,145,100,20);
panel.add(btSpnego);
btSaml2 = new JRadioButton("Saml2");
btSaml2.setBounds(60,175,100,20);
panel.add(btSaml2);
}
public void Button() {
btNext = new JButton ("Next");
btNext.setBounds(400,260,100,20);
panel.add(btNext);
}
public void Image() {
ImageIcon image = new ImageIcon("image.jpg");
lblPicture = new JLabel(image);
lblPicture.setBounds(200,20, 330, 270);
panel.add(lblPicture);
}
private void groupButton() {
ButtonGroup bg1 = new ButtonGroup( );
bg1.add(btLdap);
bg1.add(btKerbegos);
bg1.add(btSpnego);
bg1.add(btSaml2);
}
}
To display another window, you would create the window, be it a JFrame, JDialog, or what have you, and call setVisible(true) just like you do for your first window.
You ask if your other "window" should be in another class, and likely that answer is yes. Since it will have a completely different set of behaviors and goals from the first class, better to separate out concerns.
Having said that, what you plan to do, to show multiple windows is not always the best user interface design. Better often is to show multiple views using a container that uses a CardLayout.
If you want to display another window in a modal fashion, that is, have the first window wait for the second window to be processed before allowing user interaction, the second window should be a modal JDialog or JOptionPane (a JDialog in disguise).
I think for what you want to achieve, the use of a CardLayout would be appropriate.
This enables you to have multiple panels within the one frame with only one panel visible at a time and has functionality to 'flip' through the panels like a 'deck of cards'. So on initialising your frame you create the panels you want, and specify which one to start at then your next button will go to the next panel in the list.
See the tutorial here there are also some video tutorials available on youtube.
Write the two GUI's in different classes. When you start your program, start the first GUI.
FirstGUI frame1 = new FirstGUI("Title text");
frame1.setVisible(true);
Then, in the action listener code for the button you call "next"...
frame1.setVisible(false); //if you want to save the frame
frame1.dispose(); //if you want to kill the frame
SecondGUI frame2 = new SecondGUI("Title text");
frame2.setVisible(true);
I have a weird problem with modal dialogs and undecorated JFrame.
If I create a main undecorated JFrame then I display a modal dialog thanks to the JOptionPane, everything goes well. The modal dialog stays always on top and I can't click on the main fame.
But, if create another JFrame (or another JDialog), the modal dialog still prevent me to interact with the main frame, but now the modal dialog is not always on top and go underneath the main frame when I click on it.
This problem doesn't happen:
if the main frame is decorated
or if the second frame is not visible
EDIT
I use jdk1.7.0.0_09 on Linux Suse.But I have the same result with jre 1.6.0_32
The code I used to test:
public static void main(String[] args) {
// creates main frame and set visible to true
final JFrame mainFrame = new JFrame();
mainFrame.setUndecorated(true); // if I comment this line, everything goes well
mainFrame.add((new JPanel()).add(new JButton("OK")));
mainFrame.setSize(new Dimension(500, 500));
mainFrame.setVisible(true);
// creates a dialog and set visible to true
JFrame anotherFrame = new JFrame();
anotherFrame.setVisible(true); // or if I comment this line, everything goes well too
// display a modal dialog
JOptionPane.showMessageDialog(mainFrame, "A message");
}
But, if create another JFrame (or another JDialog), the modal dialog
still prevent me to interact with the main frame, but now the modal
dialog is not always on top and go underneath the main frame when I
click on it.
not true at all, both are not accesible untill JOptioPane is visible
JOptionPane or JDialod.setModal(true) block mouse or key events to the alll windows invoked from currnet JVM
there must be something else that isn't clear from your question, rest of code, minor could be Java version and Native OS
code for Java6 (winxp), works for me on Win7 / Java7(x.x_011)
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Main {
private JFrame mainFrame = new JFrame();
private JFrame anotherFrame = new JFrame();
public Main() {
mainFrame.setUndecorated(true);
mainFrame.add((new JPanel()).add(new JButton("OK")));
mainFrame.setSize(new Dimension(100, 60));
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
anotherFrame.setVisible(true);
anotherFrame.setLocation(110, 0);
anotherFrame.setSize(new Dimension(100, 60));
anotherFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(mainFrame, "A message");
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Main main = new Main();
}
});
}
}