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.
Related
I am new(ish) to Java Swing but I have not been able to find an elegant solution to my issue so I thought I'd raise a question here.
I am trying to make my current JPanel change to another JPanel based on a button click event from within the current JPanel. In essence just hiding one panel and displaying the other. I feel this can be done within my MainFrame class however I'm not sure how to communicate this back to it. Nothing I am trying simply seems to do as desired, I'd appreciate any support. Thanks
App.java
public static void main(final String[] args) {
MainFrame mf = new MainFrame();
}
MainFrame.java
public class MainFrame extends JFrame {
public MainFrame(){
setTitle("Swing Application");
setSize(1200, 800);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
// First Page Frame switch
getContentPane().add(new FirstPage());
}
}
FirstPage.java
public class FirstPage extends JPanel {
public FirstPage() {
setVisible(true);
JButton clickBtn = new JButton("Click");
clickBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
// Change to SecondPage JPanel here.
}
});
add(clickBtn);
}
}
SecondPage.java
public class SecondPage extends JPanel {
public SecondPage() {
setVisible(true);
add(new JLabel("Welcome to the Second Page"));
}
}
Any more information needed, please ask thanks :)
I think the best way is to use CardLayout. It is created for such cases. Check my example:
public class MainFrame extends JFrame {
private CardLayout cardLayout;
public MainFrame() {
super("frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cardLayout = new CardLayout();
getContentPane().setLayout(cardLayout);
getContentPane().add(new FirstPage(this::showPage), Pages.FIRST_PAGE);
getContentPane().add(new SecondPage(this::showPage), Pages.SECOND_PAGE);
setLocationByPlatform(true);
pack();
}
public void showPage(String pageName) {
cardLayout.show(getContentPane(), pageName);
}
public static interface PageContainer {
void showPage(String pageName);
}
public static interface Pages {
String FIRST_PAGE = "first_page";
String SECOND_PAGE = "second_page";
}
public static class FirstPage extends JPanel {
public FirstPage(PageContainer pageContainer) {
super(new FlowLayout());
JButton button = new JButton("next Page");
button.addActionListener(e -> pageContainer.showPage(Pages.SECOND_PAGE));
add(button);
}
}
public static class SecondPage extends JPanel {
public SecondPage(PageContainer pageContainer) {
super(new FlowLayout());
add(new JLabel("This is second page."));
JButton button = new JButton("Go to first page");
button.addActionListener(e -> pageContainer.showPage(Pages.FIRST_PAGE));
add(button);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
}
}
CardLayout is the right tool for the job.
You can simply create the ActionListener used to swap pages in JFrame class, and pass a reference of it to FirstPage:
import java.awt.CardLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
public MainFrame(){
setTitle("Swing Application");
setSize(1200, 800);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
//Create card layout and set it to the content pane
CardLayout cLayout = new CardLayout();
setLayout(cLayout);
//create and add second page to the content pane
JPanel secondPage = new SecondPage();
add("SECOND",secondPage);
//create an action listener to swap pages
ActionListener listener = actionEvent ->{
cLayout.show(getContentPane(), "SECOND");
};
//use the action listener in FirstPage
JPanel firstPage = new FirstPage(listener);
add("FIRST", firstPage);
cLayout.show(getContentPane(), "FIRST");
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
class FirstPage extends JPanel {
public FirstPage(ActionListener listener) {
JButton clickBtn = new JButton("Click");
clickBtn.addActionListener(listener);
add(clickBtn);
}
}
class SecondPage extends JPanel {
public SecondPage() {
add(new JLabel("Welcome to the Second Page"));
}
}
I am currently creating a GUI with internalFrame. This is how my code looks like:
import javax.swing.*;
public class GUI extends JFrame {
private JDesktopPane desktop;
private JMenuBar menuBar;
private JMenu startMenu;
private JMenuItem travelInfo;
private JButton updateData;
public GUI()
{
desktop = new JDesktopPane();
updateData = new JButton("Update");
createFrame();
setContentPane(desktop);
setJMenuBar(buildMenu());
}
private JMenuBar buildMenu()
{
menuBar = new JMenuBar();
startMenu = new JMenu("Start");
menuBar.add(startMenu);
travelInfo = new JMenuItem("TravelInfo");
startMenu.add(travelInfo);
return menuBar;
}
protected void createFrame()
{
NewFrame frame = new NewFrame();
frame.add(updateData);
frame.setVisible(true);
desktop.add(frame);
}
}
And then my other class:
import javax.swing.JInternalFrame;
class NewFrame extends JInternalFrame {
public NewFrame() {
setSize(800, 600);
}
}
And my main:
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
GUI frame = new GUI();
frame.setSize(800, 600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
What I want to do is to make the internalFrame that I create unsizeable so that it will always be as big as the JDesktopPane which is unsizeable. I am then going to add different menu option so that I can switch between the different frames so it kinda looks like a website. I am also wondering how I change the size of my button inside my internalFrame. I tried setting the frame.setResizable(false); for the internalFrame but it didn't work. Setting a size on the button didn't work out either... Somebody got an idea on how to solve this?
I want the JPanel at the center of the frame to be replaced when the corresponding buttons present in the JPanel to the left of the frame are pressed.
I am using cardlayout for replacing the panels in the center.
here is the sample code that i used for changing panels on button click ,but it doesn't work. can anyone let me know whats wrong in the code.
Library extends JFrame
Public Library(){
Container container = getContentPane();
container.setLayout( new BorderLayout() );
setExtendedState(JFrame.MAXIMIZED_BOTH);
banner = new BannerPanel();
container.add(banner,BorderLayout.NORTH);
MenuButtons = new MenuButtonPanel();
container.add(MenuButtons,BorderLayout.WEST);
SelectedButtonPanel = new SelectedPanel(container);
setLocationRelativeTo(null);
setVisible( true );
init();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
MenuButtonPanel extends JPanel and has multiple buttons in it. The inner class of it ButtonHandler implements hte actionListner for the buttons
//inner class
class ButtonEventHandler implements ActionListener {
public void actionPerformed( ActionEvent event ){
SelectedPanel selectObj = new SelectedPanel();
if("about".equals(event.getActionCommand()))
{
selectObj.showReplacePanel("about");
}
else if("checkout".equals(event.getActionCommand()))
{
selectObj.showReplacePanel("checkout");
}
else if("search".equals(event.getActionCommand()))
{
selectObj.showReplacePanel("search");
}
The SelectedPanel should display the replaced Jpanel in the center of the frame
public SelectedPanel() {}
public SelectedPanel(Container framePane)
{
addSelectedPanel(framePane);
}
public void addSelectedPanel(Container framePane)
{
cardPanel = new JPanel();
//set layout of panel
cardPanel.setLayout(new CardLayout());
cardPanel.setBorder(null);
cardPanel.setForeground(new Color(0, 0, 0));
//this.selObj = selObj;
aboutPanel = new About();
checkoutPanel = new Checkout();
searchPanel = new Search();
cardPanel.add(aboutPanel,ABOUTBUTTON);
cardPanel.add(checkoutPanel,CHECKOUTBUTTON);
cardPanel.add(searchPanel, SEARCHBUTTON);
framePane.add(cardPanel, BorderLayout.CENTER); }
The selectedPanel class also has method showReplacePanel() which is called in the actionPerformed of the buttonClick.
public void showReplacePanel(String selObj)
{
System.out.println("cardlayout entered");
CardLayout cl = (CardLayout)(cardPanel.getLayout());
System.out.println("cardlayout entered");
switch(selObj){
case "about":
cl.show(cardPanel,ABOUTBUTTON);
break;
case "search":
//this.repPanel = searchPanel;
cl.show(cardPanel,SEARCHBUTTON);
break;
case "checkout":
cl.show(cardPanel,CHECKOUTBUTTON);
//this.repPanel = checkoutPanel;
break;
I created an example for you, take a look at the actionPerformed(ActionEvent e) method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelSwap extends JPanel implements ActionListener {
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
public PanelSwap() {
super(new BorderLayout());
firstPanel.setBackground(Color.RED);
secondPanel.setBackground(Color.YELLOW);
JButton swap1 = new JButton("SwapToYellow");
swap1.addActionListener(this);
JButton swap2 = new JButton("SwapToRed");
swap2.addActionListener(this);
firstPanel.add(swap1);
secondPanel.add(swap2);
add(firstPanel);
}
/** Listens to the buttons and perfomr the swap. */
public void actionPerformed(ActionEvent e) {
for (Component component : getComponents())
if (firstPanel == component) {
remove(firstPanel);
add(secondPanel);
} else {
remove(secondPanel);
add(firstPanel);
}
repaint();
revalidate();
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("PanelSwap");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new PanelSwap();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
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();
}
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