i'm developing a JFrame which has a button to show another JFrame. On the second JFrame i want to override WindowsClosing event to hide this frame but not close all the application. So i do like this:
On second JFrame
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
private void formWindowClosing(java.awt.event.WindowEvent evt) {
this.dispose();
}
but application still close when i click x button on the windows. why? can you help me?
I can't use
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
because i need to show again that JFrame with some information added in it during operations from first JFrame. So i init second JFrame with attribute visible false. if i use dispose i lose the information added in a second moment by the other JFrame. so i use
private void formWindowClosing(java.awt.event.WindowEvent evt) {
this.setVisible(false);
}
but it still continue to terminate my entire app.
don't create a new JFrame, for new container use JDialog, if you want to hide the JFrame then better would be override proper e.g DefaultCloseOperations(JFrame.HIDE_ON_CLOSE), method JFrame.EXIT_ON_CLOSE teminating current JVM instance simlair as calll for System.exit(int)
EDIT
but it still continue to terminate my entire app.
1) then there must be another issue, your code maybe call another JFrame or formWindowClosing <> WindowClosing, use implemented method from API
public void windowClosing(WindowEvent e) {
2) I'b preferred DefaultCloseOperations(JFrame.HIDE_ON_CLOSE),
3) use JDialog instead of JFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClosingFrame extends JFrame {
private JMenuBar MenuBar = new JMenuBar();
private static JFrame frame = new JFrame();
private static JFrame frame1 = new JFrame("DefaultCloseOperation(JFrame.HIDE_ON_CLOSE)");
private static final long serialVersionUID = 1L;
private JMenu File = new JMenu("File");
private JMenuItem Exit = new JMenuItem("Exit");
public ClosingFrame() {
File.add(Exit);
MenuBar.add(File);
Exit.addActionListener(new ExitListener());
WindowListener exitListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
frame.setVisible(false);
/*int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}*/
}
};
JButton btn = new JButton("Show second JFrame");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame1.setVisible(true);
}
});
frame.add(btn, BorderLayout.SOUTH);
frame.addWindowListener(exitListener);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setJMenuBar(MenuBar);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ClosingFrame cf = new ClosingFrame();
JButton btn = new JButton("Show first JFrame");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
}
});
frame1.add(btn, BorderLayout.SOUTH);
frame1.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame1.setPreferredSize(new Dimension(400, 300));
frame1.setLocation(100, 400);
frame1.pack();
frame1.setVisible(true);
}
});
}
}
Adding a New Code with no WindowListener part as explained by #JBNizet, the very right thing. The default behaviour just hides the window, nothing is lost, you simply have to bring it back, every value inside it will remain as is, below is the sample program for further help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFrames
{
private SecondFrame secondFrame;
private int count = 0;
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JFRAME 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
secondFrame = new SecondFrame();
secondFrame.createAndDisplayGUI();
secondFrame.tfield.setText("I will be same everytime.");
JPanel contentPane = new JPanel();
JButton showButton = new JButton("SHOW JFRAME 2");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
secondFrame.tfield.setText(secondFrame.tfield.getText() + count);
count++;
if (!(secondFrame.isShowing()))
secondFrame.setVisible(true);
}
});
frame.add(contentPane, BorderLayout.CENTER);
frame.add(showButton, BorderLayout.PAGE_END);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFrames().createAndDisplayGUI();
}
});
}
}
class SecondFrame extends JFrame
{
private WindowAdapter windowAdapter;
public JTextField tfield;
public void createAndDisplayGUI()
{
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
tfield = new JTextField(10);
addWindowListener(windowAdapter);
contentPane.add(tfield);
getContentPane().add(contentPane);
setSize(300, 300);
}
}
Is this what you want, try this code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFrames
{
private SecondFrame secondFrame;
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JFRAME 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
secondFrame = new SecondFrame();
secondFrame.createAndDisplayGUI();
secondFrame.tfield.setText("I will be same everytime.");
JPanel contentPane = new JPanel();
JButton showButton = new JButton("SHOW JFRAME 2");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (!(secondFrame.isShowing()))
secondFrame.setVisible(true);
}
});
frame.add(contentPane, BorderLayout.CENTER);
frame.add(showButton, BorderLayout.PAGE_END);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFrames().createAndDisplayGUI();
}
});
}
}
class SecondFrame extends JFrame
{
private WindowAdapter windowAdapter;
public JTextField tfield;
public void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
tfield = new JTextField(10);
windowAdapter = new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
};
addWindowListener(windowAdapter);
contentPane.add(tfield);
getContentPane().add(contentPane);
setSize(300, 300);
}
}
You could avoid the listener completely and use
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Note that the default value is HIDE_ON_CLOSE, so the behavior you want should be the default behavior. Maybe you registered another listener that exits the application.
See http://docs.oracle.com/javase/6/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation%28int%29
It's hard to pinpoint exactly why you are experiencing the behavior stated without seeing a little more of the set-up code, however it may be due to defaultCloseOperation set to EXIT_ON_CLOSE.
Here's a link to a demo displaying the properties you are looking for although the structure is a bit different. Have a look: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/FrameworkProject/src/components/Framework.java
Related
I want to increase the value of my counter to 10 when I click on a button.
It works so far, but I don't know how to get the new counted value globally to
use it in other methods.
Here is a simple code:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
public class Test {
public JTextPane textpane=new JTextPane();
public JPanel panel;
public JButton button = new JButton("count!");
public static int counter=10;
Test() {
addListener();
panel = new JPanel(new BorderLayout());
panel.add(textpane, BorderLayout.CENTER);
panel.add(button, BorderLayout.SOUTH);
createFrame();
}
private void addListener() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
counter=counter+10;
textpane.setText("counter is set to -> "+counter);
}
});
System.out.println("new value >> "+counter);
}
private void createFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(400, 200);
frame.setVisible(true);
}
public static void main(String[] args) { new Test(); }
}
How can I get the new counter value globally?
I have tried to add my jPanel to a jDialog and when I trigger the button nothing happens. Why? I have the code below:
public class fontFormat{
public void fontPanel(){
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.getPreferredSize();
Dimension size = new Dimension();
size.width = 400;
size.height = 600;
panel.setPreferredSize(size);
panel.add(new JLabel("label"));
panel.add(new JButton("button"));
JDialog fontDialog = new JDialog();
fontDialog.add(fontDialog);
}
}
Here:
JDialog fontDialog = new JDialog();
fontDialog.add(fontDialog);
You appear to be trying to add your JDialog to itself, which should cause your code to not function. While this code may compile, running this method should cause the JVM to throw an IllegalArgumentException on the fontDialog.add(fontDialog); line.
Please note that you show a JDialog similar to how you show a JFrame:
When you call your JDialog constructor, you will want to pass in the parent window into it, especially if your desire is to display a modal dialog.
You will also want to pass into the constructor the correct ModalityType enum.
You give your JDialog content, often a JPanel with your components on it.
You pack it
then you call setVisible(true) on it, and it should display
For example,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogEg {
private static void createAndShowGUI() {
MainPanelGen mainPanelGen = new MainPanelGen();
JFrame frame = new JFrame("DialogEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanelGen.getMainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class MainPanelGen {
private JPanel mainPanel = new JPanel();
private JTextField field = new JTextField(10);
private JButton btn = new JButton(new BtnActn());
private JDialog dialog;
private DialogPanel dialogPanel = new DialogPanel();
public MainPanelGen() {
mainPanel.add(field);
mainPanel.add(btn);
field.setEditable(false);
field.setFocusable(false);
}
public JPanel getMainPanel() {
return mainPanel;
}
private class BtnActn extends AbstractAction {
BtnActn() {
super("Button");
}
#Override
public void actionPerformed(ActionEvent arg0) {
if (dialog == null) {
Window win = SwingUtilities.getWindowAncestor(mainPanel);
if (win != null) {
dialog = new JDialog(win, "My Dialog",
Dialog.ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true); // here the modal dialog takes over
System.out.println (dialogPanel.getFieldText());
field.setText(dialogPanel.getFieldText());
}
}
}
class DialogPanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton exitBtn = new JButton(new ExitBtnAxn("Exit"));
public DialogPanel() {
add(field);
add(exitBtn);
}
public String getFieldText() {
return field.getText();
}
private class ExitBtnAxn extends AbstractAction {
public ExitBtnAxn(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent arg0) {
Window win = SwingUtilities.getWindowAncestor(DialogPanel.this);
if (win != null) {
win.dispose();
}
}
}
}
I have two classes here: MainScreen and QueryScreen. MainScreen has already implemented one JTabbedPane on int. QueryScreen extended the MainScreen.
I tried to add one tab calling one event through QueryScreen but its not coming up on the app. Checkout please the sample code:
QueryScreen:
public class QueryScreen extends MainScreen {
private JSplitPane engineList;
final JPanel queryList = new JPanel();
public QueryScreen(){
tabbedPane.addTab( "Query List", queryList );
add( tabbedPane, BorderLayout.CENTER );
}
}
MainScreen:
public class MainScreen extends JFrame implements ActionListener {
/**
*
*/
JMenuBar bar;
JMenu file, register;
JMenuItem close, search;
ImageIcon image1= new ImageIcon("rsc/img/logo.jpg");
JLabel lbImage1;
JTabbedPane tabbedPane = new JTabbedPane();
final JPanel entrance = new JPanel();
/**
*
*/
public MainScreen()
{
lbImage1= new JLabel(image1, JLabel.CENTER);
entrance.add(lbImage1);
tabbedPane.addTab( "Entrance", entrance );
add( tabbedPane, BorderLayout.CENTER );
bar= new JMenuBar();
file= new JMenu("File");
register= new JMenu("Search");
close= new JMenuItem("Close");
close.addActionListener(this);
search= new JMenuItem("Request Query");
search.addActionListener(this);
//Keyboard Shortcut
register.setMnemonic(KeyEvent.VK_S);
file.setMnemonic(KeyEvent.VK_F);
search.setMnemonic(KeyEvent.VK_R);
//Ibimage1.setVerticalTextPosition(SwingConstants.CENTER);
bar.add(file);
bar.add(register);
file.add(close);
register.add(search);
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); // Maximized Window or setSize(getMaximumSize());
setTitle("SHST");
setJMenuBar(bar);
setDefaultCloseOperation(0);
WindowListener J=new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
};
addWindowListener(J);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
Search s= new Search();
s.setVisible(true);
}
}
}
ps: the MainScreen object and the setVisible from it is coming from the run class which has only the call for this MainScreen.
How am I able to add this new tab?
Thanks in advance
Edit One:
In the future please post an SSCCE instead of copy/pasting some classes.
Here's an SSCCE of your MainScreen, with the non-essentials stripped out, and a main method added:
import java.awt.*;
import javax.swing.*;
public class MainScreen extends JFrame
{
JTabbedPane tabbedPane = new JTabbedPane();
final JPanel entrance = new JPanel();
public MainScreen()
{
tabbedPane.addTab("Entrance", entrance);
add(tabbedPane, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new MainScreen();
frame.setSize(300, 200);
frame.setVisible(true);
}
});
}
}
... and here's an SSCCE for QueryScreen:
import java.awt.*;
import javax.swing.*;
public class QueryScreen extends MainScreen
{
final JPanel queryList = new JPanel();
public QueryScreen()
{
tabbedPane.addTab("Query List", queryList);
//add( tabbedPane, BorderLayout.CENTER ); /* not needed */
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new QueryScreen();
frame.setSize(300, 200);
frame.setVisible(true);
}
});
}
}
As you can see, this works, and for the most part, all I did was remove unnecessary code and added a main to each.
If you're still having problems, please update your question with an SSCCE and post the specific problem you're having.
I am using eclipse 4.2 with Java.
I have 2 java program : AppWin.java Form1.java
AppWin.java is gui windows application with menu/menu item1.
Form1.java is a Gui Jframe
I like to call Form1.java from AppWin.java by click the menu/menu item1.
When close Form1.java, it is back to AppWin.java.
This is something like MDIFORM. I really cannot find answer.
Please help , if you know eclipse menu.
Thanks
package top;
import java.awt.EventQueue;
public class AppWin {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AppWin window = new AppWin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
...
With your help, I made a big step.
Thanks to all of you!
Next is my final demo, in windows 7, eclipse 4.2, java Gui
Hope it is helpful to others.
There are 3 parts : AppWin, Form1, Form2. AppWin is top main which call Form1 and Form2 with menu/item.
//1
package top;
import java.awt.EventQueue;
public class AppWin {
private JFrame frame;
private Form1 form1;
private Form2 form2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AppWin window = new AppWin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AppWin() {
initialize();
form1 = new Form1();
form2 = new Form2();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Menu1");
menuBar.add(mnNewMenu);
JMenuItem mntmNewMenuItem = new JMenuItem("menu item1");
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
form1.setVisible(true);
}
});
mnNewMenu.add(mntmNewMenuItem);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("menu item2");
mntmNewMenuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
form2.setVisible(true);
}
});
mnNewMenu.add(mntmNewMenuItem_1);
JMenu mnNewMenu_1 = new JMenu("Menu2");
menuBar.add(mnNewMenu_1);
JMenuItem mntmMenuItem = new JMenuItem("Menu item3");
mnNewMenu_1.add(mntmMenuItem);
}
}
//2
package top;
import java.awt.BorderLayout;
public class Form1 extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Form1 frame = new Form1();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Form1() {
// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblNewLabel = new JLabel("this Form1");
contentPane.add(lblNewLabel, BorderLayout.WEST);
textField = new JTextField();
contentPane.add(textField, BorderLayout.CENTER);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
contentPane.add(btnNewButton, BorderLayout.EAST);
}
}
//3
package top;
import java.awt.BorderLayout;
public class Form2 extends JDialog {
private final JPanel contentPanel = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Form2 dialog = new Form2();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Form2() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JLabel lblThisForm = new JLabel("This Form2");
contentPanel.add(lblThisForm);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
}
Thanks again
You better use JDesktopPane + JInternalFrame for that purpose instead. Here's a quick sample.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class JInternalFrameSample {
private JPanel pnlMain;
private JDesktopPane desk;
public JInternalFrameSample(){
pnlMain = new JPanel(new BorderLayout()){
#Override public Dimension getPreferredSize(){
return new Dimension(600,600);
}
};
desk = new JDesktopPane();
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Internal Frame");
JMenuItem item = new JMenuItem();
item.setAction(new AbstractAction("Create New") {
#Override
public void actionPerformed(ActionEvent arg0) {
JInternalFrame iFrame = new JInternalFrame("Created from Menu");
iFrame.setResizable(true);
iFrame.setClosable(true);
iFrame.setIconifiable(true);
iFrame.setSize(new Dimension(300, 300));
iFrame.setLocation(0, 0);
//iFrame.getContentPane().setLayout(new BorderLayout());
//iFrame.getContentPane().add( new YourCustomUI().getUI() );
iFrame.setVisible(true);
desk.add(iFrame);
}
});
menu.add(item);
bar.add(menu);
pnlMain.add(bar, BorderLayout.PAGE_START);
pnlMain.add(desk, BorderLayout.CENTER);
}
private JPanel getUI(){
return pnlMain;
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Demo");
frame.getContentPane().setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JInternalFrameSample().getUI());
frame.pack();
frame.setVisible(true);
}
});
}
}
See also : How to Use Internal Frames
If you do not like the JDesktopPane and JInternalFrame solution, just use your AppWin JFrame as is, and open modal JDialogs for the rest of the forms, instead of JFrames. Modal dialogs can float around the desktop and do not allow you to click your AppWin, until they are closed.
It is usually better to use just one main JFrame for an application, unless you have some wizard application that moves progressively from one JFrame to the other and back. Even with a wizard app, you can stick with one JFrame and update progressively just the ContentPane with JPanels.
Here is the AppWin JFrame:
public class AppWin extends javax.swing.JFrame {
private Form1 form1;
private Form1 form2;
...
private FormN formN;
public AppWin() {
initComponents();
form1 = new Form1(this, true);
form2 = new Form2(this, true);
...
formN = new FormN(this, true);
}
...
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
form1.setVisible(true);
}
And here is your Form1 JDialog:
public class Form1 extends javax.swing.JDialog {
public Form1(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
...
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
setVisible(false);
}
I only use NetBeans for GUI building because that's more convenient. In the following I can tell you how to achieve what you want to do but I can't tell you how to layout all the components because NetBeans do that for me.
So basically you want to 1. show secondFrame by clicking a menuitem and then close mainFrame, 2. show mainFrame after closing secondFrame, yes? Then, the key is to pass the reference of mainFrame to secondFrame, and write your own method of formClosing event of secondFrame. Something like this:
In the menuItem method in your mainframe:
private void menuItemActionPerformed(java.awt.event.ActionEvent evt) {
//pass 'this' frame's (mainFrame) reference to the secondFrame
SecondFrame newFrame = new SecondFrame(this);
newFrame.setVisible(true); //show the secondFrame
this.setVisible(false); //hide this frame (mainFrame)
}
In your secondFrame:
public class SecondFrame extends javax.swing.JFrame {
private MainFrame mainFrame;
//define your own constructor that can use mainFrame's reference
public SecondFrame(MainFrame mainFrame) {
initComponents();
this.mainFrame = mainFrame;
}
private void initComponents(){
//bind your own event for closing second frame
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
/***********your stuff***************/
}
//show mainFrame when closing this frame and then dispose this frame
private void formWindowClosing(java.awt.event.WindowEvent evt) {
mainFrame.setVisible(true);
this.dispose();
}
}
The codes above is for disposing the secondFrame when closing it. If you just want to hide the secondFrame when closing for future use, then the codes will be slightly different. Let me know what you up to.
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
form1.setVisible(true);
dispose();
}
Lets say, we have a few JFrame windows visible in same time and for each window JDialog appears. When our windows in cascading mode and for dialogs setAlwaysOnTop is true then all dialogs will be visible over last window.
I just want to associate a Dialog component with its owner, so that when you'll be switching between Frames you'll get only one dialog on top and won't lose this dialog when click on a frame.
Dialogs have constructor like this:
setAlwaysOnTop(true);
setModal(false);
Thanks in advance!
How to make JDialog onTop only for his parent?
setParent in the constructor properly
have to use setModalityType f.e. ModalityType.DOCUMENT_MODAL ModalityType.APPLICATION_MODAL instead of setModal
setModal is valid to the container which intialized / is parent for this JDialog
don't to use more than one JFrame, use JDialog instead, reuse this container for another action
for example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SuperConstructor extends JFrame {
private static final long serialVersionUID = 1L;
public SuperConstructor() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300, 300));
setTitle("Super constructor");
Container cp = getContentPane();
JButton b = new JButton("Show dialog");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
FirstDialog firstDialog = new FirstDialog(SuperConstructor.this);
}
});
cp.add(b, BorderLayout.SOUTH);
JButton bClose = new JButton("Close");
bClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
});
add(bClose, BorderLayout.NORTH);
pack();
setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
SuperConstructor superConstructor = new SuperConstructor();
}
});
}
private class FirstDialog extends JDialog {
private static final long serialVersionUID = 1L;
FirstDialog(final Frame parent) {
super(parent, "FirstDialog");
setPreferredSize(new Dimension(200, 200));
setLocationRelativeTo(parent);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
JButton bNext = new JButton("Show next dialog");
bNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
SecondDialog secondDialog = new SecondDialog(parent, false);
}
});
add(bNext, BorderLayout.NORTH);
JButton bClose = new JButton("Close");
bClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});
add(bClose, BorderLayout.SOUTH);
pack();
setVisible(true);
}
}
private int i;
private class SecondDialog extends JDialog {
private static final long serialVersionUID = 1L;
SecondDialog(final Frame parent, boolean modal) {
//super(parent); // Makes this dialog unfocusable as long as FirstDialog is visible
setPreferredSize(new Dimension(200, 200));
setLocation(300, 50);
setModal(modal);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("SecondDialog " + (i++));
setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
JButton bClose = new JButton("Close");
bClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});
add(bClose, BorderLayout.SOUTH);
pack();
setVisible(true);
}
}
}
In the API one of JDialog constructor is JDialog(Dialog owner, boolean modal) which means that you can create a dialog and specify the parent container as well as the modality. In the modal section, setting it to true means that this dialog will be modal and you cannot access the parent window while the dialog is in display.
But again, you can use the setModal() method to accomplish the same.
just set the Model true and Just set Relativelocation(parent); and dont use setontop(true) for the JDialog.
and then if u back open that time u will get dialog ontop every time. but that will be differ when u Drag the Parent Frame.
I managed to solve this problem building a focus listener that does this job. You can then set this listener to the window you want the dialog stays always visible until is closed. Here is what worked for me:
public class WindowFocusListenerDialogFocus implements WindowFocusListener {
private JFrame _dialogFrame;
public WindowFocusListenerDialogFocus(JFrame dialogFrame) {
_dialogFrame = dialogFrame;
}
#Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Focus lost!");
}
#Override
public void windowGainedFocus(WindowEvent e) {
System.out.println("Focus gained!");
_dialogFrame.toFront();
}
}