Close a JFrame from a button?

How do I close a JFrame using a JButton to trigger the event? I want to dispose of the frame.
thanks

I think this peace of code should do it for you:
public class MyFrame extends JFrame{
private MyFrame() {
this.setTitle("MyFrame");
Container contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout());
// Close the application using a JButton.
JButton closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
contentPane.add(closeButton, BorderLayout.SOUTH);
// Close the application using the JFrame.
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);

Similar Messages

  • Another JFrame from a Button Click

    Hi...
    I was just wondering how I could write a code where I could bring up another JFrame (let say JFrame2) from a button click on a main JFrame (let say JFrame1)......
    Could anyone show me an example......
    Thanks
    Ashley Q

    Thanks.........
    Btw, I am trying to output 2 different JFrame, by clicking 2 JButtons. On JFrame frame, there's 2 button, the Synthesizer Button which bring up the Synthesizer JFrame and the Recognizer Button which bring up the Recognizer JFrame. However, there's a some problems probably with my coding......Could someone help me...
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class VoicePronunciationSystem extends JFrame implements ActionListener
         public Component createComponents()
              JButton RecognizerButton = new JButton ("Recognizer");
              RecognizerButton.setMnemonic('r');
              RecognizerButton.addActionListener(this);
              JButton SynthesizerButton = new JButton ("Synthesizer");
              SynthesizerButton.setMnemonic('s');
              SynthesizerButton.addActionListener(this);
              JLabel label = new JLabel ("This is a Voice Pronunciation System");
              JPanel panel = new JPanel();
              panel.setBorder(BorderFactory.createEmptyBorder(120,120,120,120));
              panel.setLayout(new GridLayout(1, 1));
              panel.add(label);
              panel.setLayout(new GridLayout(2, 2));
              panel.add(RecognizerButton);
              panel.setLayout(new GridLayout(2, 3));
              panel.add(SynthesizerButton);
              return panel;
         public void actionPerformed(ActionEvent event)
              Object source = event.getSource();
              if( source == RecognizerButton) {
                   JFrame frame2 = new JFrame("Recognition");
                   frame2.getContentPane().add(new JTextField(20));
                   frame2.pack();
                   frame2.setVisible(true);
              if( source == SynthesizerButton) {
                   JFrame frame3 = new JFrame("Synthesizer");
                   frame3.getContentPane().add(new JTextField(20));
                   frame3.pack();
                   frame3.setVisible(true);
         public static void main(String[] args)
              try
                   UIManager.setLookAndFeel(
                   UIManager.getCrossPlatformLookAndFeelClassName());
              } catch (Exception e) { }
              JFrame frame = new JFrame("VoicePronunciationSystem");
              //JFrame frame2 = new JFrame ("Recognition");
              //JLabel label = new JLabel ("This is a Voice Pronunciation System");
              //frame.getContentPane().add(label);
              VoicePronunciationSystem sys = new VoicePronunciationSystem();
              Component contents = sys.createComponents();
              frame.getContentPane().add(contents, BorderLayout.CENTER);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
    }

  • Create multiple JFrame from a button

    I would like to create a new JFrame each time I click on a Button.
    How could I do that?
    Thanks

    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class dfray extends JFrame implements ActionListener,
                                                 ItemListener {
      JButton makeFrameButton, showFramesButton;
      JLabel frameLabel;
      JComboBox comboBox;
      final static int
        OFFSET_X = 30,
        OFFSET_Y = 40;
      int frameCount = 0;
      Map frameMap;
      public dfray() {
        frameMap = new HashMap();
        makeFrameButton = new JButton("Make Frame");
        makeFrameButton.addActionListener(this);
        showFramesButton = new JButton("Show Frames");
        showFramesButton.addActionListener(this);
        JPanel northPanel = new JPanel();
        northPanel.add(makeFrameButton);
        northPanel.add(showFramesButton);
        frameLabel = new JLabel(" ", SwingConstants.CENTER);
        comboBox = new JComboBox();
        comboBox.addItemListener(this);
        comboBox.setPreferredSize(new Dimension(60,20));
        JPanel southPanel = new JPanel();
        southPanel.add(new JLabel("Focus frame"));
        southPanel.add(comboBox);
        getContentPane().add(northPanel, "North");
        getContentPane().add(frameLabel, "Center");
        getContentPane().add(southPanel, "South");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300,200);
        setLocation(200,200);
        setVisible(true);
      public void actionPerformed(ActionEvent e) {
        JButton button = (JButton)e.getSource();
        if(button == makeFrameButton)
          makeFrame();
        if(button == showFramesButton) {
          Iterator it = frameMap.keySet().iterator();
          String keys = "keyset = ";
          while(it.hasNext())
            keys += it.next() + ", ";
          frameLabel.setText(keys);
      public void itemStateChanged(ItemEvent e) {
        JComboBox comboBox = (JComboBox)e.getItemSelectable();
        Integer key = (Integer)comboBox.getSelectedItem();
        JFrame frame = (JFrame)frameMap.get(key);
        frame.toFront();
      private void makeFrame() {
        final JFrame frame = new JFrame("Frame " + ++frameCount);
        frameMap.put(new Integer(frameCount), frame);
        comboBox.addItem(new Integer(frameCount));
        frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            JFrame f = (JFrame)e.getSource();
            int index = Integer.parseInt(f.getTitle().substring(6));
            frameMap.remove(new Integer(index));
            comboBox.removeItem(new Integer(index));
            frame.dispose();
        frame.setSize(300, 200);
        frame.setLocation(500 + frameCount * OFFSET_X,
                          200 + frameCount * OFFSET_Y);
        frame.setVisible(true);
      public static void main(String[] args) {
        new dfray();
    }

  • Proper method to close a JFrame

    What is the most apropriate way to perform an action to close a JFrame when a button is click, and return the resource to the system?
    Thanks.

    U can first display the Welcomeframe whatever method u want to use
    i assume u have a Button in WelcomeFrame which will invoke the DataFrame
    If you have the following button write it as follows
    JButton myButton = new JButton("Show Data Frame");
    MyActionEvent lMyActionEvent = new MyActionEvent();
    myButton.addActionListener(lMyActionEvent);In the action event class write down the following
    class MyActionEvent implements ActionListener{
         public void actionPerformed(ActionEvent e){
              JDataFrame fJDataFrame = new JDataFrame();
              //Show or display JDataFrame here u can also do that from within the JDataframe class
              //Here get any values from fJDataFrame.
              //Because they will be lost once the frame is disposed
         //Line No 1:
              fJDataFrame.dispose();
    }In the JDataFrame class set the following property
    mJFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);Let me tell u what will happen.
    When the JDataFrame is invoked from the action listener MyActionEvent the execution will stop at the Line now 1:. Until the fJDataFrame closes. Once the control comes back dispose the frame. Meanwhile do what u want in the JDataFrame until it is visible. U can later close your WelcomeFrame
    Hope this helps

  • Closing JFrame from within frame without closing program

    Is there any way to close a JFrame from within frame without closing the program. I don't want to just frame.setVisible(false);

    http://search.java.sun.com/search/java/index.jsp?col=javaforums&qp=%2Bforum%3A31&qt=closing+JFrame+from+within+frame+without+closing+program+&x=5&y=11
    Happy New Year!

  • How can I stop a JFrame from closing when clicking the close button.

    I need to display a dialog when a user attempts to close my app, giving them the option to close, minimize or cancel. How can I stop the form from closing after the user makes his selection? I have the folllowing code, but my form still closes after selecting an option:
    private void formWindowClosing(java.awt.event.WindowEvent evt) {                                  
            //An array of Strings to be used a buttons in a JOptionDialog
            String[] options = {"Close", "Minimize", "Cancel"};
            //Determines what the user wants to do
            int result = JOptionPane.showOptionDialog(null, "What to you want to do?  Close the application, minimize or cancel?", "Please select an option...", 0, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
           //Determines what to do, depending on the user's choice
            if (result == 0) {
                //Close the application
                System.exit(0);
            } else if (result == 1) {
                //Minimize the application
                this.setState(Frame.ICONIFIED);
        }Any help would be much appreciated!

    import java.awt.event.*;
    import javax.swing.*;
    public class test extends JFrame {
         public static void main( String[] args ) {
              new test();
         public test() {
              setSize( 200, 200 );
              //the next line makes the JFrame not close
              setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE );
              //now add a listener that does the trick
              addWindowListener( new WindowAdapter() {
                        public void windowClosing( WindowEvent e ) {
                             //ask the user and do whatever you wish
              setVisible( true );
    }

  • Can not add a picture to the JFrame from an ActionListener class

    As topic says, I can not add a picture to the JFrame from an ActionListener class which is a class inside the JFrame class.
    I have a Map.java class where I load an image with ImageIcon chosen with JFileChooser.
    I my window class (main class), I have following:
    class OpenImage_Listener implements ActionListener
         public void actionPerformed(ActionEvent e)
              int ans = open.showOpenDialog(MainProgram.this);     // "open" is the JFileChooser reference
              if(ans == open.APPROVE_OPTION)
                   File file = open.getSelectedFile();                    
                   MainProgram.this.add(new Map(file.getName()), BorderLayout.CENTER);     // this line does not work - it does not add the choosen picture on the window,
                            //but if I add the picture outside this listener class and inside the MainProgram constructor, the picture apperas, but then I cannot use the JFileChooser.
                            showMessageDialog(MainProgram.this, fil.getName() ,"It works", INFORMATION_MESSAGE);  // this popup works, and thereby the ActionListener also works.
    }So why can�t I add a picture to the window from the above listener class?

    The SSCCE:
    Ok, I think I solved it with the picture, but now I cannot add new components after adding the picture.
    Look at the comment in the actionlistener class:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Test extends JFrame{
         JButton b = new JButton("Open");
         JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
         Picture pane;
         Test(){
              super("Main Program");
              setLayout(new BorderLayout());
              JPanel north = new JPanel();
              add(north, BorderLayout.NORTH);
              north.add(b);
              b.addActionListener(new Listener());
              setVisible(true);
              setSize(500,500);
              pane = new Picture("");
              add(pane, BorderLayout.CENTER);
         class Listener implements ActionListener {
              public void actionPerformed(ActionEvent e){
                   int ans = jfc.showOpenDialog(Test.this);
                   if(ans == jfc.APPROVE_OPTION)
                        File file = jfc.getSelectedFile();
                        Test.this.add(new Picture(file.getName()), BorderLayout.CENTER);
                        pane.add(new JButton("NEW BUTTON")); // Why does this button not appear on the window???
                        pane.repaint();
                        pane.revalidate();
         public static void main(String[] args)
              Test t = new Test();
    class Picture extends JPanel
         Image pic;
         String filename;
         Picture(String filename)
              setLayout(null);
              this.filename = filename;
              pic = Toolkit.getDefaultToolkit().getImage(filename);
            protected void paintComponent(Graphics g)
                super.paintComponent(g);
                g.drawImage(pic,0,0,getWidth(),getHeight(),this);
                revalidate();
    }

  • Adobe Presenter 9 and PowerPoint 2013 - Missing Import Audio from PowerPoint button

    I am only able to intermitantly use the Import button in Adobe Presenter 9 to Import Audio from PowerPoint. Why would I be able to do it on some presentations but not all? I thought it was an audio conversion issue but even when I convert the audio (when prompted by PowerPoint) it doesn't always allow me to import it.

    I have found a solution if the original PowerPoint was a ppt file, follow these steps:
    File > Save As a pptx file
    Close PowerPoint (this helps with not corrupting the file)
    Re-open the pptx file
    File > Convert
    Save with a new file name (this helps with not corrupting the file)
    You should now have the Import from Presentation button if you go to the Presenter tab and click the Import button
    I have not found a solution for pptx files yet.

  • How to close Acrobat.exe from the task manager processes through plug-in?

    I have a plug-in in which we have a functionality of defining some keys and they are displayed as annotations on the PDF. Now, if the user defines such a key, an annot (i.e.a rectangular box) gets displayed on the PDF and if the user does not click custom menu say 'Close Key' then annot remains visible on the PDF.
    My problem is if in such a case i.e. the user has defined a key & if the user does not hit 'Close Key' and instead closes Acrobat by directly hitting close (i.e. [X] button at top right corner), then Acrobat exits; but the Acrobat.exe remains running in the Processes.
    If the user tries to open the same PDF again then a message pops up saying 'Cannot open file for viewing as its already in use...'.
    Note that any other PDF gets opened fine.
    Could somebody help me in giving me any ideas/suggestions on this? I want to exit the acrobat.exe from the processes so that the same PDF could get opened. As described above, the cause is the key (annot) was opened and user abrubtly exited Acrobat. Is there a way, that we could catch this Acrobat exit event in the plug-in? That way, I'd be able to clear off the annot (key) and then close acrobat.
    Please let me know asap.

    Hey, tnx for ur response! But, the issue is reproducible on Acrobat 7.0 Professional.
    I do have the 'WillClose' event registered in my plug-in. Below is the event that is wired up with 'WillClose' event:-
    static 
    ACCB1 void ACCB2 NotifyAVWillClose (AVDoc doc, void *clientData){
    UNREFERENCED_PARAMETER(clientData);
    UNREFERENCED_PARAMETER(doc);
    CloseTemplate(TRUE);
    The 'CloseTemplate' method performs the closing of the annotation, clearing of objects and deleting the PDFfile class pointer.
    And this all works fine with Acrobat.exe getting closed from the task manager processes in acrobat versions 8 & 9. However, in Acrobat 7.0, the process remains in the Task Manager.
    Could you suggest any ideas on what else needs to be implemented to end the process in Acrobat 7?
    Thanks!

  • How can we close the window using a button in applet?

    I have a close button in my applet which should close the browser from where the application is launched. Can somebody post a sample code for doing the same?

    I'm afraid I don't have any sample code, but I can describe a possible solution.
    1. Retrieve the JSObject via Application.[url http://docs.oracle.com/javafx/2/api/javafx/application/Application.html#getHostServices%28%29]getHostServices().[url http://docs.oracle.com/javafx/2/api/javafx/application/HostServices.html#getWebContext%28%29]getWebContext()
    2. Use the JSObject to manipulate the JavaScript into closing the Window.

  • Calling modal JFrame from  JFrame?? is it possible

    query desc:
    i have created a frame and there is a button on that frame.
    on push of the button i want a modal frame to open up..
    i am unable to make this modal its modless by default in my code.
    or
    how to put a frame inside a Jdialog
    and calling JDIalog from a button on another frame.
    any help ???

    nileshweb wrote:
    i have created a frame and there is a button on that frame.
    on push of the button i want a modal frame to open up..You can't do this.
    i am unable to make this modal its modless by default in my code.Right, again you can't do this.
    how to put a frame inside a Jdialog
    and calling JDIalog from a button on another frame.And you can't do this either.
    What you need to do is create a class that creates a JPanel, not a JFrame. In your main application (that's within a JFrame) when the JButton is pushed, create a modal JDialog (or perhaps better a JOptionPane) and place the created JPanel in the dialog or optionpane and then show. This will work, and fairly easily.
    Usually even my main application is created in a JPanel (I'm trying not to subclass unless absolutely necessary), and I add the JPanel to a JFrame when I want to show this main app. Later, if I decide that I want to show the main app as a JApplet, it's a trivial thing to just create the JApplet, add my main JPanel to it, and show the JApplet. Programming this way increases your flexibility tremendously.

  • How to close the browser from an Applet?

    Hi,
    I've written one applet, with 2 buttons (Continue & Exit). On click of Continue button, it will open another web page. On click of Exit button, the browser should be closed.
    I'm not able to close the browser from the applet.
    Can any body help me.
    Rgds
    Santosh

    In my experience, calling Javascript from applets is flaky at best. However, I have gotten it to work in some cases. The following code should get you started:
    netscape.javascript.JSObject win = netscape.javascript.JSObject.getWindow(applet);
    Now you can call different methods on the win object (look into Javascript documentation for details).
    It also depends on if you are using the Java Plug-in or the JVM built into the web browser. You probably need set MAYSCRIPT=TRUE in your HTML. Look into the Java Plug-in documentation for details...

  • Bug Report: [VIsio 2010] whenever I try to save a diagram to JPEG and then close Visio using the X button, Visio hangs

    Greetings
    I use Visio 2010 in windows 7 64bit
    and I have this problem:
     whenever I try to save a diagram to JPEG (save as>JPEG) and then close Visio using the X button on the upper right corner, then Visio hangs.
    The jpeg pic is saved ok, but Visio hangs permanently: I have to close it using task manager.
    On the other hand, if after I save into jpeg, I press whatever other button in Visio (from ribbon) then it works ok, and afterwards I can close Visio with the X button
    - but, if I try to close Visio with the X button  right after saving to JPEG, Visio will surely hang.
    Thank you
    PS. Visio 2010 is fully updated (File>Help reports:
    Visio 2010 Premium (v14.0.6111.5000) SP1 MSO (14.0.6112.5000) 32bit)

    Update:
    The problem reappeared/wasn't completely solved:
    So, I also went to Control Panel>add/remove programs, rightclick on Adobe Acrobat X> change installation and untick the PDFMaker item, in order to uninstall it:
    that's because initially, even after I had unticked "PDFMaker for Visio AddIn" in COM Add-Ins,
    in File>Options>Add-Ins tab, on the Active Application Add-Ins part (yes, on ACTIVE Add-Ins)
    I was still seeing about 5-6 lines, all having items containing PDFMaker for Visio AddIn" [PDFMVisio.vsl].
    In other words, the PDFMVisio.vsl file was loaded even if unticked!!
    Then, after uninstalling the add-in, the problem was finally fixed at last!
    Thank you so much for this additional information!  I was having the same problem.  I did what you instructed, and the problem has now disappeared!

  • Creating a pop up text window from a button within an Applet

    I want to create an applet with two clickable buttons in it (this I know how to do). When a visitor to the site clicks on one of the buttons, I want a separate window to pop up and display a few lines of text. A different text message will be displayed depending upon which button was clicked.
    I can't figure out how to create a pop up window when the button is clicked. In fact I'm not even sure that this is possible as the user must have the facility to close the window after they have read the text, and from my limited knowledge of Java and applets this would involve system exit() ??? and this is not allowed.
    I am new to Java and would appreciate any help that anyone can offer.
    Thanks
    Jim

    Write the popup frame as if you were writing an application, but don't set the close operation. From the applet just setVisible(true) and again, don't worry about the close issue.
    Visit my website, any of the samples except button, to see windows popping from applets.

  • Why always i need to close Firefox.exe from task manager when visiting some websites?

    Hello dear Mozilla team! I just defaced to the problem , when i'm trying to visit http://cyberprogrammers.net/ website from Firefox browser, its frozen and i need to close firefox.exe from task manager. <a href="http://cyberprogrammers.net/">Cyber Programmers</a> website is working perfect with other browsers, and i try to open it with my friends computer, with Firefox browser and i don't get any error like that, its not frozen. So please help me to understand the problem and solve it. I'm using Latest version of firefox, Windows 8.1. Thanks for your support!

    Hello,
    '''Try Firefox Safe Mode''' to see if the problem goes away. [[Troubleshoot Firefox issues using Safe Mode|Firefox Safe Mode]] is a troubleshooting mode that turns off some settings, disables most add-ons (extensions and themes).
    If Firefox is open, you can restart in Firefox Safe Mode from the Help menu:
    *Click the menu button [[Image:New Fx Menu]], click Help [[Image:Help-29]] and select ''Restart with Add-ons Disabled''.
    If Firefox is not running, you can start Firefox in Safe Mode as follows:
    * On Windows: Hold the '''Shift''' key when you open the Firefox desktop or Start menu shortcut.
    When the Firefox Safe Mode window appears, select "Start in Safe Mode".<br>
    [[Image:Safe Mode Fx 15 - Win]]
    '''''If the issue is not present in Firefox Safe Mode''''', your problem is probably caused by an extension, and you need to figure out which one. Please follow the [[Troubleshoot extensions, themes and hardware acceleration issues to solve common Firefox problems]] article to find the cause.
    ''To exit Firefox Safe Mode, just close Firefox and wait a few seconds before opening Firefox for normal use again.''
    When you figure out what's causing your issues, please let us know. It might help others with the same problem.

Maybe you are looking for