Second JFrame closes first - java

two JFrames,
JFrame Main; // Main JFrame
JFrame Sub; //Second JFrame that is initialized from within Main via a JMenuItems ActionListener.
mainMenuItem.setActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try{
Sub subFrame = new Sub();
subFrame.setVisible(true);
}catch(Exception e){}
}
});
}
The problem is whenever i close the second JFrame (Sub) it closes the first aswell.
Both JFrames have:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Is that part of the problem?

EXIT_ON_CLOSE means to exit the program immediately (System.exit()) when the frame is closed.
You probably want to set this to DISPOSE_ON_CLOSE, then add a WindowListener and close the program only if both frames have been closed.
(Or, perhaps you want only the main frame to have EXIT_ON_CLOSE)

Yes. JFrame.EXIT_ON_CLOSE by definition exits the application. For your second Frame use DISPOSE_ON_CLOSE or HIDE_ON_CLOSE.
Hope this helps!

You state:
JFrame Sub; //Second JFrame that is initialized from within Main via a JMenuItems ActionListener.
This suggests you've a design problem:
Your 2nd "frame" shouldn't even be a JFrame since it is not behaving as a separate independent main program window.
Instead it's acting as a dialog since it is dependent on and shown from a parent window, the main JFrame. So make the secondary window a JDialog not a JFrame, and all these problems will go away.
You will need to consider whether it should be a modal dialog where the main window is not accessable to the user while the dialog is open, or a non-modal dialog.
Having said that, you may even be better off using one window/JFrame and swapping views via a CardLayout.
Please read this link: The Use of Multiple JFrames, Good/Bad Practice?, and in particular please have a look at Andrew Thompson's community wiki answer.

Related

JAVA - How do I make the user be able to utilize only the frame on top?

When two JFrames are enabled, I want the user to be able to use only one in the top (think of that like an error pop up on your screen, when you can't press anything but the popup itself). I am aware of the class JInternalFrame and I chose not to use it for my program. Thanks in advance :)
Use JDialog, you can set your main frame as the JDialog's parent frame, so that whenever your main frame and JDialog will display, you will be able to click only the JDialog, not your main frame.
You want a modal behaviour, then. I think you can try using JDialog instead of JFrame, something like:
JDialog dialog = new JDialog(parentFrame, title, true); //parameters: owner, title and modal
dialog.getContentPane().add(somePanel);
dialog.pack();
dialog.setVisible(true);
You can read more about it here: http://docs.oracle.com/javase/tutorial/uiswing/misc/modality.html

Switch between multiple JFrames

I'm relatively new to Java and I'm trying to make some kind of quiz. I created 3 JFrames, all in the same package. On my main frame, there are two buttons (one for the english version and the other one for the german version). I want to switch JFrames after pressing these buttons (so that I can, by pressing "English", see and interact with my english quiz frame). Looking it up didn't help me the slightest, because I'm not really experienced with it. Is it even possible to do it like this? If not, how could I do it?
The standard approach is to use the Card Layout, which allows you to use the same JFrame as you populate it with different things at different points in your application. So initially, your JFrame would show the loading screen, then the user presses a button and you load a new set of components without discarding the current JFrame you have. In some cases, you might also need to make some size adjustments.
It is difficult to say without seeing any code, but usually, what is done is that you do something like so:
new Frame(args);
this.dispose();
The code above assumes that the constructor of Frame takes care of launching and making the components visible. The this.dispose(); disposes of the current JFrame (assuming your class extends JFrame).
You have two buttons in your frame 1 right? So first, double click the button which says "English". Lets say the variable name for that button is jButton1. Inside that button type this.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
EnglishFrame eng = new EnglishFrame();
eng.setVisible(true);
}
Then double click the other button which says "German" (jButton2). Inside that type this.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
GermanFrame german = new GermanFrame();
german.setVisible(true);
}
this.dispose() - This will cause the jFrame window to close
Then you create an object of the other two forms. (In your case the form for English and Germany)
.setVisible(true) - This will show you the form.
Create a single Jframe window. After that create JPanels with all the compenents such as buttons, textfields and labels you want. Make sure the panel is the same size as your Jframe. Panel's work about the same as JFrame's, code wise.
This code will stitch everything together for you:
panel.setSize(Jframe.getSize()) //That wont
panel.add(button); //Just remember you need to add more code to position the buttons correctly.
//If you using netbeans builder:
//You just have to use this one line in the constructor/intialiser method
frame.add(panel); //This will add the panel to the Jframe/Window
//No need to add extra code for positioning.
If you want to swap between the panels. In the button press method, use this
frame.setContentPane(panel); //panel = panel you want to change too.
frame.repaint(); //Ensures that the frame swaps to the next panel and doesn't get stuck.
frame.revalidate(); //Ensures that the frame swaps to the next panel and doesn't get stuck.
When you first start the java application you have to set the content pane or else it will appear as a blank window.
frame.setContentPane(panel); //Starting Panel
frame.setVisible(true); //Make the frame visible
Sorry if the explanation is bad, I don't have enough time to explain it fully.

Optional way to close a dialog window

I'm using a custom JFrame to implement a simple dialog in a Java application I'm working on.
After the user pushes the 'Apply' button in the window, it should close.
What would be the most conventional way to do this? Is setVisible(false) inside the class the best way? Is there any way more recommended?
To close a window in Swing like JFrame or JDialog you have two options.
Call dispose()
Just call dispose() method:
public void dispose()
Releases all of the native screen resources used by this Window, its
subcomponents, and all of its owned children. That is, the resources
for these Components will be destroyed, any memory they consume will
be returned to the OS, and they will be marked as undisplayable.
For instance:
frame.dispose();
dialog.dispose();
Dispatch a WINDOW_CLOSING event
You can dispatch a new WindowEvent like this:
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
If the window has attached a WindowListener it will be notified. If the frame's (or dialog's) default close operation is set then this action will be performed. The possible close operations are:
DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do anything;
require the program to handle the operation in the windowClosing
method of a registered WindowListener object.
HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the
frame after invoking any registered WindowListener objects.
DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and
dispose the frame after invoking any registered WindowListener
objects.
EXIT_ON_CLOSE (defined in JFrame and not available for JDialog): Exit the application using the System exit method. Use this only in applications.
It depends on what you're trying to achieve. Setting the window to not visible will simply hide it but it will still be running in the background (JFrame/InternalFrame). You can use JDialog (See JOptionPane as an example) to create temporary frames which are truly closed when clicking on one of the buttons. You can also retrieve the selected option when the user closed the window (here : Javadoc). You can also forcibly close a window by firing an event to close it, like so:
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(
new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)
)
Inside an actionlistener for example.
There are multiple operations which can be performed when you close a JFrame.
Suppose you have a JFrame
JFrame frame = new JFrame();
This one exits the JVM when closed.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This one just hides the JFrame.
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
This one disposes the JFrame.
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate
And the default is do nothing.
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

Closing a Frame from a Panel

Let me first explain the situation,
I have a class with a JPanel called panelclass.
It's method getPanel() returns the JPanel.
In a JFrame class called frameclass, I create a new object of panelclass, got its panel and added it to the frame pane.
What I am trying to achieve is, when a button in paneclass is clicked, It should close this JFrame ie.frameclass.
I donot know how a panelclass can communicate back to the frameclass to close.
I tried this.dispose() and super.dispose() but was not successful even after extending JFrame
Is there a simpler way?
Please do help.
There are a few was to achieve this, but the simplest is probably through the use of SwingUtilities.getWindowAncestor(Component)
This will return the Window that the component was added to or null if it has no parent window. From there you can simply call Window#dispose to close the frame.
when a button in paneclass is clicked, It should close this JFrame
See Closing an Application. I prefer using something like the `ExitAction' described there. The reason is that your application will behave just like the user clicked on the close button of the frame which means that if you have any WindowListeners added to the window they will be invoked.

How do I make a button in a Java Applet that opens a JFrame?

I've made a few JFrames and I want to call them from a JApplet. What is the best way to do this? Could I just instantiate my JFrames in my init method and then call them whenever a button is pushed?
How do I make a button in a Java Applet that opens a JFrame?
You probably shouldn't do this, but rather if you want to open another window from the JApplet, create and show a JDialog. They are created and displayed similar to a JFrame, but uses different constructors. You will need to get the applet's Window for the "owner" parameter of the JDialog, and this can be obtained via:
Window w = (Window) SwingUtilities.getAncestorOfClass(Window.class, comp);
Where comp is a visible component in the JApplet.
Ok, it sounds like you initialize a JFrame on initialization and you store it. You don't need to re-instantiate the JFrame from initalization. Instead just store it in a field of your Applet and use it when ever the button is pressed.
OR you can use Singletons and lazy initialization:
class JFrameToOpen extends JFrame {
private static JFrame frame = null;
private JFrameToOpen() {
//init
}
public static GetJFrame() {
if(frame==null) {
frame=new JFrameToOpen();
}
return frame;
}
}
But singletons are ugly and many people choose to avoid them.
You can just create JFrame with its default constructor and then show it:
JFrame frame = new JFrame();
JLabel label = new JLabel("Welcome");
frame.add(label);
frame.pack();
frame.setVisible(true);
This code forks from the applet similar way as from the standalone program. No need for any special tricks. The applet itself then can only contain buttons like "press to launch the application".

Categories

Resources