System.exit(0) closing both JFrames

hey, ive got a problem with a JFrame
Ive got 1 JFrame that currently holds a JMenuBar, 2 JMenus and in the 1st JMenu there are 4 JMenuItems.
One of the JMenuItems uses an ActionListener to lauch another JFrame, but when the 2nd JFrame is finished (and System.exit(0) launches), the first JFrame closes as well. What is going on??
code follows:
THE MAIN JFRAME
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class realframe extends JFrame
protected JMenuItem[] m_fontMenus;
protected JCheckBoxMenuItem m_showPatList;
protected JCheckBoxMenuItem m_showPatData;
protected JCheckBoxMenuItem m_showHRGraph;
protected JCheckBoxMenuItem m_showBPGraph;
protected JCheckBoxMenuItem m_showTempGraph;
public realframe(){
super("PMS Menu GUI");
setSize(450, 350);
JMenuBar menuBar = createMenuBar();
setJMenuBar(menuBar);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
addWindowListener(wndCloser);
setVisible(true);
//start Menus
protected JMenuBar createMenuBar()
final JMenuBar menuBar = new JMenuBar();
//creates File
JMenu mFile = new JMenu("File");
//Menu 1 item 1 : : : Add Patient
JMenuItem item = new JMenuItem("Add Patient");
ActionListener lst = new ActionListener() //ActionListener for Add Patient
public void actionPerformed(ActionEvent e)
new realgui( new JFrame() );
item.addActionListener(lst);
mFile.add(item);
//Menu 1 item 2 : : : Delete Patient
item = new JMenuItem("Delete Patient");
lst = new ActionListener()
public void actionPerformed(ActionEvent e) { }
item.addActionListener(lst);
mFile.add(item);
//Menu 1 item 3 : : : Search
item = new JMenuItem("Search");
lst = new ActionListener()
public void actionPerformed(ActionEvent e) { }
item.addActionListener(lst);
mFile.add(item);
//Divider
mFile.addSeparator();
//Menu 1 item 4 : : : Exit
item = new JMenuItem("Exit");
item.setMnemonic('x');
lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
item.addActionListener(lst);
mFile.add(item);
menuBar.add(mFile);
//end menu item 1
ActionListener viewListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateMonitor();
JMenu mView = new JMenu("View");
mView.setMnemonic('V');
//Menu 2 item 1 : : : Patient List Toggle
m_showPatList = new JCheckBoxMenuItem("Patient List");
m_showPatList.setMnemonic('L');
m_showPatList.setSelected(true);
m_showPatList.addActionListener(viewListener);
mView.add(m_showPatList);
//Menu 2 item 2 : : : Data box Toggle
m_showPatData = new JCheckBoxMenuItem("Patient Data");
m_showPatData.setMnemonic('D');
m_showPatData.setSelected(true);
m_showPatData.addActionListener(viewListener);
mView.add(m_showPatData);
//Divider
mView.addSeparator();
//Menu 2 item 3 : : : HR Graph toggle
m_showHRGraph = new JCheckBoxMenuItem("Show HR Graph");
m_showHRGraph.setMnemonic('H');
m_showHRGraph.setSelected(true);
m_showHRGraph.addActionListener(viewListener);
mView.add(m_showHRGraph);
//menu 2 item 4 : : : BP Graph Toggle
m_showBPGraph = new JCheckBoxMenuItem("Show BP Graph");
m_showBPGraph.setMnemonic('B');
m_showBPGraph.setSelected(true);
m_showBPGraph.addActionListener(viewListener);
mView.add(m_showBPGraph);
//menu 2 item 5 : : : Temp Graph Toggle
m_showTempGraph = new JCheckBoxMenuItem("Show Temp Graph");
m_showTempGraph.setMnemonic('T');
m_showTempGraph.setSelected(true);
m_showTempGraph.addActionListener(viewListener);
mView.add(m_showTempGraph);
menuBar.add(mView); //adds the menu
return menuBar;
protected void updateMonitor() { }
public static void main(String argv[]) { new realframe(); }
THE SECONDARY JFRAME
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class realgui extends JDialog implements ActionListener
JTextField surname;
JTextField given;
JTextField age;
JTextField doctor;
JTextField phone;
Patient patient = new Patient();
JRadioButton radiomale;
JRadioButton radiofemale;
public realgui( JFrame frame )
super( frame, true );
System.out.println("in 1");
setTitle( "Add A New Patient" );
setSize( 400, 250 );
JPanel panel = new JPanel( new BorderLayout() );
panel.setLayout( new GridBagLayout() );
panel.setBorder( new EmptyBorder( new Insets( 5, 5, 5, 5 ) ) );
getContentPane().add( BorderLayout.CENTER, panel );
GridBagConstraints c = new GridBagConstraints();
Dimension shortField = new Dimension( 40, 20 );
Dimension mediumField = new Dimension( 100, 20 );
Dimension longField = new Dimension( 180, 20 );
EmptyBorder border = new EmptyBorder( new Insets( 0, 0, 0, 10 ) );
EmptyBorder border1 = new EmptyBorder( new Insets( 0, 20, 0, 10 ) );
c.insets = new Insets( 2, 2, 2, 2 );
c.anchor = GridBagConstraints.WEST;
JLabel lbl1 = new JLabel( "Surname:" );
lbl1.setBorder( border );
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
panel.add( lbl1, c );
surname = new JTextField();
surname.setPreferredSize( longField );
c.gridx = 1;
c.gridwidth = 3;
panel.add(surname, c );
JLabel lbl7 = new JLabel( "Given Name:" );
lbl7.setBorder( border );
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
panel.add( lbl7, c );
given = new JTextField();
given.setPreferredSize( longField );
c.gridx = 1;
c.gridwidth = 3;
panel.add(given, c );
JLabel lbl2 = new JLabel( "Age:" );
lbl2.setBorder( border );
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
panel.add( lbl2, c );
age = new JTextField();
age.setPreferredSize( shortField );
c.gridx = 1;
c.gridwidth = 3;
panel.add( age, c );
JLabel lbl3 = new JLabel( "Gender:" );
lbl3.setBorder( border );
c.gridx = 0;
c.gridy = 3;
panel.add( lbl3, c );
JPanel radioPanel = new JPanel();
radioPanel.setLayout( new FlowLayout( FlowLayout.LEFT, 5, 0 ) );
ButtonGroup group = new ButtonGroup();
radiomale = new JRadioButton( "Male" );
radiomale.setSelected( true );
group.add(radiomale);
radiofemale = new JRadioButton( "Female" );
group.add(radiofemale);
radioPanel.add(radiomale);
radioPanel.add(radiofemale);
c.gridx = 1;
c.gridwidth = 3;
panel.add( radioPanel, c);
JLabel lbl4 = new JLabel( "Doctor:" );
lbl4.setBorder( border );
c.gridx = 0;
c.gridy = 4;
panel.add( lbl4, c );
doctor = new JTextField();
doctor.setPreferredSize( longField );
c.gridx = 1;
c.gridwidth = 3;
panel.add(doctor, c );
JLabel lbl5 = new JLabel( "Phone Number:" );
lbl5.setBorder( border );
c.gridx = 0;
c.gridy = 5;
c.gridwidth = 1;
panel.add( lbl5, c );
phone = new JTextField();
phone.setPreferredSize( mediumField );
c.gridx = 1;
c.gridwidth = 3;
panel.add(phone, c );
JButton submitBtn = new JButton( "Submit" );
c.gridx = 4;
c.gridy = 0;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add( submitBtn, c );
submitBtn.addActionListener(this);
JButton cancelBtn = new JButton( "Cancel" );
c.gridy = 1;
c.anchor = GridBagConstraints.NORTH; // anchor north
panel.add( cancelBtn, c );
cancelBtn.addActionListener(this);
WindowListener wndCloser = new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
addWindowListener( wndCloser );
setVisible( true );
public static void main( String[] args ) {
new realgui( new JFrame() );
public void actionPerformed(ActionEvent evt)
if (evt.getActionCommand ().equals ("Submit"))
Person person = new Person();
String surnam = surname.getText();
String give = given.getText();
String ag = age.getText();
String docto = doctor.getText();
String phon = phone.getText();
char gende;
if(radiomale.isSelected()==true)
gende = 'M';
else
gende = 'F';
System.out.println("in 2 " + surnam);
person.setSurname(surnam);
person.setGiven(give);
// person.setAge(ag);
person.setDoctor(docto);
person.setPhone(phon);
person.setGender(gende);
System.out.println(surnam + " " + give + " " + ag + " " + gende + " " + docto + " " + phon);
person.setHistory();
patient.add(person);
System.exit(0);

No, dispose() is inherited. Just replace System.exit(0); with:
setVisible(false);
dispose();I think that'll work in your code.

Similar Messages

  • Preventing System.exit()

    I've written a class loader that executes .jar files across a network from a central application. Works great - except when one of those jar files calls a System.exit().
    Since the purpose of this application is to have several applications "executing" across a network, having one of them call System.exit() kills all of them. Are there any methods of scanning the class files as they are being loaded and having code replaced? For example, searching for System.exit(someInt) or even JFrame.EXIT_ON_CLOSE and then replacing this bytecode with some more acceptable bytecode that instructs the parent program the child wishes to terminate?
    Rewriting all of the programs to be loaded so that they don't call System.exit() or its variations isn't an option here, so I'm open to any suggestions.

    BTW: Overriding system libraries is against
    standards, but does work.
    http://java.sun.com/j2se/1.4.2/docs/guide/standards/
    In java.lang.Runtime
    public void exit(int status) {
    throw new Error("Exit called with
    led with status="+status);
    }Create a jar and copy it to <java_home>/lib/endorsed
    The run the following
    public class Main {
    public static void main(String[] args) {
    System.exit(1);
    }And you will get the follow when run with this
    "modified" JRE
    "C:\Program Files\Java\jre1.6.0\bin"\java -cp .Main
    Exception in thread "main" java.lang.Error: Exit
    called with status=1
    at java.lang.Runtime.exit(Runtime.java:86)
    at java.lang.System.exit(Unknown Source)
    at Main.main(Main.java:11)
    Yes, but then it works only on your machine.

  • Closing a JFrame without using System.exit(0)

    Hello all,
    I'm writting an application at the moment that uses a JFrame as an "about box" invoked when a menu item from another JFrame is selected . The about box is set to undecorated, and I have set up an Thread to handle an animation of the credits that move up slowly. I have also added into it code to play a sound file while the credits are running.
    I wanted to have it so that the user can just click once anywhere on the Panel area of the about box, and that would close the about box window and stop the sound.
    I can get it to stop the sound on click no problem, what I'm having issues with is closing just the about box Frame. I've used System.exit(0) but this closes the original application, which I dont want it to do. I've been looking at online example code and I've found that dispose() might work... Problem is my JFrame for the about box is initiated in the main applications JFrame under an eventListener for the menuItem 'about'. The sound file is played inside the JPanel of the about box. And the listener to close it is located in the same place ( about box JPanel ).. does anyone know how to get this frame ( initiated in main applications JFrame ) and dispose of this frame through code located in the JPanel of the about box.
    I hope this is descriptive enough for you.
    Please let me know if you have any questions about my question.
    Many thanks,
    Mark.

    It seems you are asking how to find the parent frame of a Component that you know is within a frame?
    You can getParent() of the component. If it is a frame (instanceof) - dispose, else check for the getParent()...
    If you don't want to code it yourself use SwingUtilities.getWindowAncestor(Component) to get the Window in which the panel is.
    HTH
    Mike

  • Why my system tray application terminates when JFrame is closed???

    Hi,
    I am using JDK 1.6 with Netbeans 5.5 and currently trying to make an system tray application. I have one main class which runs as a system tray application and one JFrame class which will be shown when user selects a menu item from system tray. So far so good but a small problem. When the JFrame form is closed, my system tray application also closes. Can somebody tell me what am I missing?
    Thanks

    set the DefaultCloseOperation of the JFrame to DISPOSE_ON_CLOSE instead of EXIT_ON_CLOSE
    db

  • System.exit

    Before user is about to close the gui, I want to free up the open sockets used in my application. Now, we don't want to poll the exit, waiting for the open sockets to finally free themselves and than the application quits. The user is going to thing something is wrong with the application and wonder why its taking to long to exit :)
    So, I thought of putting the close sockets in a thread and start it,
    but the next line after the start thread code in the main thread code
    is System.exit. Now once that calls, the free sockets thread
    won't do any work on closing the sockets, because the JVM is realease from its resource. Now I'am damm if don't use a thread or damm if using a thread (Not doing anything).
    Can I have a Thread as another JVM to free the sockets while the application exit?
    Thanks

    Please don't crosspostimport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
        public Test() {
         setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
         Container content = getContentPane();
         JButton jb = new JButton("Exit");
         content.add(jb,BorderLayout.SOUTH);
         jb.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) {
              doFinalStuff();
         addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent we) {
              doFinalStuff();
         setSize(200,200);
         show();
        private void doFinalStuff() {
         dispose();
         for (int i=0; i<10; i++) {
             try { Thread.sleep(1000); } catch (Exception exc) {}
             System.out.println(i);
         System.exit(0);
        public static void main(String[] args) { new Test(); }
    }

  • How to intercept "System.exit"?

    I am writing a large GUI application that optionally spawns other GUI threads. These spawned threads are special-purpose text editors. It is important that the editor knows when it is about to be closed, so that it can prompt the user to save a modified file.
    The editors are based upon javax.swing.JFrame, and I have overridden the "windowClosing" method of a WindowAdapter to check file status and prompt when necessary. This method performs as desired when I close the editor window manually. However, when I close the main application (which calls System.exit(0) ), the editor frames also close without any invocation of my windowClosing method.
    Is there any way the dependent editor JFrame can be alerted that the virtual machine is about to be ended? I could probably keep a list in my main application of all the dependent processes that need to be cleanly ended, but it would be much simpler (and so much more object-oriented) if the dependent thread could take care of itself!

    MarkHausman wrote:
    As you suggested, I posted this question on the Swing forum.
    For those who are interested: the Swing solution I was offered was to make use of the static function Frame.getFrames(). This allows access to all frames launched by an application. By putting this call in my main shutdown method, I can identify all spawned editor frames and call each one's shutdown method.
    This is not as satisfying as my original desire, to have the spawned frame recognize when the VM is about to close, but it is easy enough to implement that I am going with it.And why wouldn't addShutdownHook() work?

  • Closing One JFrame instead of All JFrames?

    Hello everyone,
    I am developing a program using Sun's Forte community edition V3.0, this is for an assignment and I have chosen Java and Swing instead of the Recommended MS Access. Grin (You got to love a challenge.)
    I have a menu class that allows users to create instances of other classes by clicking various buttons representing options.
    When the user clicks a button a new class instance is created allowing the user to interact with the system.
    //-- Action in response to a buton click. This calls an instance of a working
    //-- class.
    private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {
            final JFrame fs = new SRemClassEntryFr();
            fs.setBounds(150, 150, 530, 398);
            fs.setVisible(true);
            fs.setTitle("SRemClassEntry");
            fs.setDefaultCloseOperation(HIDE_ON_CLOSE);
            fs.getContentPane().setBackground(java.awt.Color.cyan);
            fs.addWindowListener(new WindowAdapter(){
                public void windowClosed(WindowEvent e){
                    System.exit(0);
    //-- The starting class of the application. A simple class that calls other
    //-- classes based on users selecting menu items represented as buttons
    public static void main(String args[]) {
            //-- new AdminMainMenuFr().show();
            final JFrame f = new AdminMainMenuFr();
            //f.setContentPane(f.getContentPane());
            f.setBounds(150, 150, 620, 560);
            f.setVisible(true);
            f.setTitle("Admininistrator Main Menu");
            f.getContentPane().setBackground(java.awt.Color.cyan);
            f.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            f.addWindowListener(new WindowAdapter(){
                public void windowClosed(WindowEvent e){
                    System.exit(0);
        }My application is behaving itself as intended, it does have a major problem and that is...
    On selecting an operation from the Administrator menu, I am able to use and interact with that specified object instance. Unfortunately when I close the open object, it not only closes the said object but the underlying Administrator menu object also.
    Does anyone have any ideas on how I should be doing this?
    Thanks in advance
    Mark.

    fs.setTitle("SRemClassEntry");
    fs.setDefaultCloseOperation(HIDE_ON_CLOSE);
    fs.getContentPane().setBackground(java.awt.Color.cyan);
    fs.addWindowListener(new WindowAdapter(){ 
    public void windowClosed(WindowEvent e){
    System.exit(0); /// here is the problem
    });you say when the SRemClassEntry is closed, "exit the program" , (System.exit(0);)
    hope that helps

  • Can I intercept "System.exit" in a spawned GUI thread?

    I am writing a large GUI application that optionally spawns other GUI threads. These spawned threads are special-purpose text editors. It is important that the editor knows when it is about to be closed, so that it can prompt the user to save a modified file.
    The editors are based upon javax.swing.JFrame, and I have overridden the "windowClosing" method of a WindowAdapter to check file status and prompt when necessary. This method performs as desired when I close the editor window manually. However, when I close the main application (which calls System.exit(0) ), the editor frames also close without any invocation of my windowClosing method.
    Is there any way the dependent editor JFrame can be alerted that the virtual machine is about to be ended? I could probably keep a list in my main application of all the dependent processes that need to be cleanly ended, but it would be much simpler (and so much more object-oriented) if the dependent thread could take care of itself!

    I was not aware of the Frame.getFrames() method; this is apparently good enough to find all the dependent windows I have created. Thanks for pointing this out.
    As to the spawned threads, perhaps you could comment on my method. I was actually hoping to open the editors as independent applications that would persist after the main GUI was closed. To do this, I gave my editor class an associated static Runnable, like so:
       public static class Starter extends Thread {
             String[] arguments = new String[0];
             public void run() {
                MyEditor re = new MyEditor();
                if( arguments.length > 0) re.setFileName(arguments[0]);
                re.setVisible(true);
             public void copyArguments( String[] args) {
                arguments = Arrays.copyOf(args, args.length);
       }which I invoked from my main GUI in the following code:
       Starter starter = new Starter();
       String[] startArgs = {"myfilename.txt", "more parameters"};
       starter.copyArguments(startArgs);
       starter.setDaemon(false);
       starter.start();This does indeed start the editor, but it is in the same virtual machine, since the editor stops when the GUI stops. Is this method setting me up for trouble? Is there a way to do what I originally wanted, starting the editor in a new virtual machine?

  • Why won't System.exit(0)  work?

    does System.exit(0); work with an event handler?
    I'm making a quit menu button, and I want my program to quit when it is clicked...unfortunately, System.exit(0); is not working...can soemone please help?
    thanks!

    here's all mmy code......i'm really at a loss...i can't figure anything out......
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    public class SafetyMapView extends JFrame {
         // These are the tiles and buttons
         private JPanel               tiles;
         private JButton[]          buttons;
         private JCheckBox           editWallsButton;
         private JCheckBox           selectExitsButton;
         private JButton           computePlanButton;
         private JCheckBox           showDistancesButton;
         private JButton           resetButton;
         private JMenuBar          theMenuBar;
         private JMenu               fileM;
         private JMenuItem          openM,saveM,quitM;
         private JFileChooser      showIt;
         public void setJMenuBar(JMenuBar aMenuBar){theMenuBar=aMenuBar;}
         public JButton getFloorTileButton(int i) { return buttons; }
         public JPanel getTilePanel() { return tiles; }
         public JCheckBox getEditWallsButton() { return editWallsButton; }
         public JCheckBox getSelectExitsButton() { return selectExitsButton; }
         public JButton getComputePlanButton() { return computePlanButton; }
         public JCheckBox getShowDistancesButton() { return showDistancesButton; }
         public JButton getResetButton() { return resetButton; }
         public JFileChooser getJFileChooser() { return showIt; }
         public JMenuItem getOpen() { return openM;}
         public JMenuItem getSave() { return saveM;}
         public JMenuItem getQuit() { return quitM;}
         // This constructor builds the panel
         public SafetyMapView(String title, FloorPlan floorPlan) { 
              super(title);
              // Create the panel with the floor tiles on it      
              createFloorPlanPanel(floorPlan);
              // Layout the rest of the window's components
    setupComponents();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(600, 500);
    setVisible(true);
    // Create the panel to contain the buttons that display the floor plan
    private void createFloorPlanPanel(FloorPlan floorPlan) {
         // Setup the panel with the buttons
    buttons = new JButton[floorPlan.size()*floorPlan.size()];
    tiles = new JPanel();
    tiles.setLayout(new GridLayout(floorPlan.size(),floorPlan.size()));
              // Add the buttons to the tile panel
    for (int r=0; r<floorPlan.size(); r++) {
         for (int c=0; c<floorPlan.size(); c++) {
              int i = r * floorPlan.size() + c;
              buttons[i] = new JButton();
              buttons[i].setBorder(BorderFactory.createLineBorder(Color.lightGray));
              buttons[i].setBackground(Color.white);
              tiles.add(buttons[i]);
         public void setOpenHandler(java.awt.event.ActionListener x){
         /*public void setSaveHandler(java.awt.event.ActionListener x){
                   int option = 0;
                   java.io.File sel = null;
                   java.io.File[] files = null;
                   String filename = null;
                   javax.swing.JFileChooser chsr = new javax.swing.JFileChooser();
                   option = chsr.showSaveDialog(null);
                   switch (option)
                   case javax.swing.JFileChooser.APPROVE_OPTION :
                   //do something
                        a.dispose();
                        break;
                   case javax.swing.JFileChooser.CANCEL_OPTION :
                   sel = null;
                   break;
                   case javax.swing.JFileChooser.ERROR :
                   sel = null;
                   break;
                   default :
                   sel = null;
                   break;
                   chsr.setEnabled(false);
                   //do something
                   return;
                   //DO something...//
    // Here we add all the components to the window accordingly
    private void setupComponents() {
         // Layout the components using a gridbag
    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints layoutConstraints = new GridBagConstraints();
    getContentPane().setLayout(layout);
    // Add the tiles
    layoutConstraints.gridx = 0; layoutConstraints.gridy = 1;
    layoutConstraints.gridwidth = 1; layoutConstraints.gridheight = 7;
    layoutConstraints.fill = GridBagConstraints.BOTH;
    layoutConstraints.insets = new Insets(2, 2, 2, 2);
    layoutConstraints.anchor = GridBagConstraints.NORTHWEST;
    layoutConstraints.weightx = 1.0; layoutConstraints.weighty = 1.0;
    layout.setConstraints(tiles, layoutConstraints);
    getContentPane().add(tiles);
    JMenuBar myMenuBar = new JMenuBar();
    layoutConstraints.gridx = 0; layoutConstraints.gridy = 0;
    layoutConstraints.gridwidth = layoutConstraints.gridheight = 1;
    layoutConstraints.fill=GridBagConstraints.NONE;
    layoutConstraints.insets = new Insets(2, 2, 2, 2);
    layoutConstraints.anchor = GridBagConstraints.NORTHWEST;
    layoutConstraints.weightx = 0.0; layoutConstraints.weighty = 0.0;
    layout.setConstraints(myMenuBar, layoutConstraints);      
              JMenu fileMenu = new JMenu("File");
              myMenuBar.add(fileMenu);
              fileMenu.setMnemonic('F');
              JMenuItem openM = new JMenuItem("Open Floor Plan");
              fileMenu.add(openM);
              openM.setMnemonic ('O');
              JMenuItem saveM = new JMenuItem("Save Floor Plan");
              fileMenu.add(saveM);
              saveM.setMnemonic ('S');
              JMenuItem quitM = new JMenuItem("Quit");
              fileMenu.add(quitM);
              quitM.setMnemonic ('Q');
              getContentPane().add(myMenuBar);
    public static void main(String args[]){
         //try{
         new SafetyMapView("Fire Safety Routes", FloorPlan.example1());
         //catch(java.io.FileNotFoundException e){
         //     e.printStackTrace();
    I cut out the parts where all the other buttons are being added to the layout cuz it was really relaly long....

  • System.exit doesnt work on Sun OS 5.7 ??

    Hi, I have encountered a kind of wierd problem. I have a small application that uses System.exit when the user wants to shut down the application.
    That works fine in Windows but in Sun OS 5.7 the application just freeze.
    Im using java version:
    java version "1.4.1"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1-b21)
    Java HotSpot(TM) Client VM (build 1.4.1-b21, mixed mode)
    Would be greatful if someone could help me.
    This code is an small example of my application.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ExitTest extends JFrame implements ActionListener {
    JButton jButton1 = new JButton();
    public ExitTest() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String[] args) {
    new ExitTest().setVisible(true);
    private void jbInit() throws Exception {
    jButton1.setText("Exit");
    jButton1.addActionListener(this);
    addWindowListener(this);
    this.getContentPane().add(jButton1, BorderLayout.SOUTH);
    public void actionPerformed(ActionEvent e) {
    this.setVisible(false);
    System.out.println("Exiting");
    try {
    System.exit(0);
    } catch(SecurityException ex) {
    ex.printStackTrace();
    ---------------------------------------------------------------------------------------------------------

    Hmm, sorry about that, my misstake, that line is still there from an erlier attempt to use windowlisteners instead ... that line should not be there ...

  • System.exit(0)   error in program.

    Any help appreciated. Let me first put my code here:
    Converts money using CurrencyConverter, there's another class I haven't posted here!! (which calculates conversion)
    import java.util.* ;
    public class CurrencyConverterTester
      public static void main(String[] args)
        Scanner in = new Scanner(System.in) ;
        System.out.println("How many euros is one dollar?") ;
        String input = in.nextLine() ;
        double rate = Double.parseDouble(input) ;
        CurrencyConverter myconverter = new CurrencyConverter(rate);
        System.out.println("Dollar value (Q to quit)") ;
        input = in.nextLine() ;
        while (true) {
          if (input == "Q"){
            System.exit(0);
            break;}
          else {
          System.out.println(input + " dollar = " +  myconverter.convert(Double.parseDouble(input)) + " euros");
          input = in.nextLine();
          continue;}   
    }The issue is that the program won't terminate when I enter Q as my input?? I'm guessing it might have something to do my conversion from string to double in the 'else' statement, but not sure. Also, if you can suggest a more simpler method for the last 'while' statement, that would be helpful as well. Thanks. (noob to java)

    paulcw wrote:
    Curse Gosling for making &#43; syntactic sugar for string append, but not overloading any other operators.@Paul
    What did you expect from a duck ;-)
    Seriously, yep, maybe it would have been better for noobs if the syntax of Java Strings was consistent with other kinds of Object... or maybe it would have been better if == was compiler-magiced into stringA.equals(stringB)... and the left and right shift operators have promise, and of course that way lies MADNESS, as witnessed in C&#43;&#43; ;-)
    @OP... You are (IMHO) using the break, continue and especially System.exit() inappropriately... see my comments in your code...
        System.out.println("Dollar value (Q to quit)") ;
        input = in.nextLine() ;
        // while-true-loops are a "fairly usual" way of doing this kind of stuff,
        // but that doesn't make them "the preferred option". Typically you would
        // explore more "vanilla approaches" (which don't rely on the break and
        // continue statements)... leaping straight to the "tricky approach" means
        // you haven't (most often out of sheer laziness) thought it through... and
        // ALL good computer programs are thoroughly thought through (yep, try
        // saying that three times fast, especially after three beers).
        while (true) {
          // You don't compare Strings using ==
          if ( "Q".equalsIgnoreCase(input) ) {
            // Either of the following statements will do the job. The call to exit
            // will exit the JVM, therfore the break statement cannot be reached,
            // so it is superflous, so it's presence is just a bit confusing. Having
            // said that, "real programmers" don't use System.exe routinely, only in
            // the case of an emergency, such as handling a fatal-error, such as an
            // out-of-memory condition... an even then it's usually indicative of a
            // poor "system design", because it terminates the JVM which is running
            // this program without giving anything else in the program a chance to
            // clean-up after itself... like ask the user if they want to save there
            // work, or whatever.
            // I would use break (if anything) instead of System.exit
            // ... and if I wrote the Java tutorials, exit wouldn't be mentioned at
            // all until both "normal" flow control, and exception handling had both
            // been thoroughly covered.
            System.exit(0);
            break;
          } else {
            // I would break this line up, probably into three lines, simply becuase
            // it's syntatically "a long line".
            // Also the name "myconverter" doesn't tell what the class is/does.
            // IMHO, currencyConverter would be a better (more meaningful) name.
            // HERE'S HOW I WOULD WRITE IT
            // double dollars = Double.parseDouble(input);
            // double euros = currencyConverter.convert(dollars);
            // System.out.println(input + " dollar = " + euros + " euros");
            System.out.println(input + " dollar = " +  myconverter.convert(Double.parseDouble(input)) + " euros");
            input = in.nextLine();
            // This continue statement is superflous. continue says "go back to the
            // top of loop, reevaluate the loop-condition (true in this case) and
            // (if the condition is still true) "Play it again Sam".
            // ... which is exactly what will happen without this continue statement
            // and hence (IMHO) your code is easier to follow without it, simply
            // because another programmer may waste there time trying to figure out
            // WHY that continue statement is present.
            continue;
        }*ALSO:* The format of that code totally sucks. Braces all over the place; improper indentation. No wonder you're struggling to read your own code. Please read and abide the [The Java Code Conventions|http://java.sun.com/docs/codeconv/] (at least until you have the requisite experience to formulate credible and compelling arguments as to why your "style" is superior to the standard, and that's no small ask). Yes this is *important*... trust me on this (for now)... especially if you are going to ask for help on the forums... You're effectively wasting our time asking us to decipher your code because you are too lasy to format it correctly... and I for one find that "self entitled" attitude ugly, and offensive... Help us help you... you know?
    And BTW.... Here's how I would actually do it.... no funky while-true, break, or continue... just a plain-ole'-while-woop....
    package forums;
    import java.util.Scanner;
    public class KRC
      private static final Scanner SCANNER = new Scanner(System.in);
      public static void main(String[] args) {
        try {
          String input = null;
          while ( !"Q".equalsIgnoreCase(input=enterDollarAmount()) ) {
            System.out.println(input + " dollars is " +  Double.parseDouble(input) + " euros.");
            System.out.println();
        } catch (Exception e) {
          e.printStackTrace();
      private static String enterDollarAmount() {
        System.out.print("Please enter an amount in dollars : ");
        return SCANNER.nextLine();
    }Edited by: corlettk on 25/10/2009 10:21 ~~ Distant Monarching Forum Markup!

  • How stop call to System.exit but allow them to install Securitymanager?

    I have an application that allows you to start a java application from inside it (it then gives you monitoring capabilities). I want this to work with pretty much any desktop application, even those that require their own security manager. However, i don't want their application to be able to shutdown the jvm. How can I do this?
    As far as I can tell, there's no way to allow them to add the securitymanager, "wrapped" by mine is there?
    And I thought of using AccessController.doPriviledgedAction(...) and giving them a context where they can add a security manager but not call system.exit, but then if they do add a security manager, won't it have the final say on system.exit calls?
    Is there a solution here?

    6tr6tr wrote:
    Thanks for the reply!
    Hmmm, the problem with that is I need the users to be able to use my application without access to that app's source code. So they need to be able to run that program (as 3rd party black-boxed code) inside my app and still have this work properly. Is there another way?
    Source code?
    You don't need any source code for what I suggested.
    If a frame/jframe tries to exit on close, I can grab and stop that. my problem is if some random code tries to call system.exit(). Is there any other way to intercept it?
    UPDATE: the only solution i could come up with is to use bytecode engineering + classloading.
    Which I doubt will help if they call it with reflection.
    You could use the bootstrap command line options and replace System with your own version. Add some functionality to how it sets up the security manager and/or make System.exit() do nothing, but provide another name for yourself.

  • System.exit(o) in Swing

    Hi,
    In my Swing application, as soon as I start the main() method, a dialog containing Username and Password fields with OK and Cancel buttons gets popped-up. I have a propertyChangeListener which gets notified when Ok or cancel is pressed and when Cancel is pressed, System.exit(0) is called to exit the JVM.
    So, there are two threads running -
    One - the main thread which invokes the dialog pop-up
    Second - the propertychangelistener which calls the System.exit(0) on pressing Cancel button.
    So, at times, after pressing cancel button, the application does not exit but invokes the previously running thread (main thread). But this does not happen always.
    Could you please let me know why the application does not terminate completely and how to resolve this?
    Thanks in advance!

    Hi,
    As I had already mentioned in my previous post -
    Here is the pseudo-code which fails to terminate on pressing Cancel button at times.
    ================The Login dialog code=============
    public LoginDialog()
    // Other code
    JOptionPane optionPane = new JOptionPane(array, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
    optionPane.addPropertyChangeListener(new PropertyChangeListener()
    public void propertyChange(PropertyChangeEvent e)
              Object value = optionPane.getValue();
              if (value.equals(YES))
              else
    // user closed dialog or clicked cancel
    setVisible(false);
    System.exit(0);
    ===============The main thread===================
    This main() method calls the logindialog with username and passwrd as parameters.
    So, initially, the main() thread is started and the login dialog is displayed. On pressing Cancel in this dialog, the control goes to propertyChangeListener of the loginDialog() and calls System.exit(0) which should terminate the entire application, but at times, the previously running main thread is resumed and the application is not terminated.
    Please clarify why this happens.
    Thanks in advance!!
    });

  • System.exit(0) closes wrong window

    I use a web browser to display an applet.
    In the applet I have the possibility to start a new webbrowser window with myapplet.getAppletContext().showDocument(url, "_blank");In the new webpage I also start a new applet.
    To close this new web page I call System.exit(0); from the applet in the new page.
    The strang thing that happens than is that the parent window is closed and the newly opened web page is still active.
    If I open these windows myself in the browser, I can close them from the applet.
    Can anybody help.

    System.exit is not permitted by an applet for the above mentioned reason.
    Multiple browser windows with applets share the same jvm so exiting the
    jvm makes the other applets crash.
    When you give the applet permission (sign or policy) system.exit will crash
    the browser.
    It is possible to close a popup window, since I don't beleve in the JSObject
    anymore (crashed too many times with too many bugs in mozilla).
    You can use another way, here it is.
    in your applet// to open the window
    this.getAppletContext().showDocument(
         new URL("javascript: myPopupWindow = window.open('yourPage.htm');myPopupWindow.focus()"));
    // to close the window
    this.getAppletContext().showDocument(
         new URL("javascript: myPopupWindow.close()"));in your html page:<script>
    var myPopupWindow = null;
    </script>

  • Using System.exit(0) in executeScript

    When using System.exit(0) in executeScript within a process, it shuts down JBoss. This happens both
    in LC ES2.5 and ADEP  10.0.1.20111108.1.309370
    I would expect that System.exit(0) simply ends the script and returns control to the process. Am I
    missing something here?
    TIA,
    Alex

    gavas_java_nov26_exception wrote:
    If i use System.exit(0) in the try block or catch block will finally block will be executed?
    try
    System.exit(0);
    catch(Exception e){
    System.exit(0);     
    finally
    System.out.println("finally!");
    To tell you the truth, What does it matter? You shouldn't be doing that anyway, at least not in a well written program.
    But, if you really want to find out, do as duffymo said, and try it. It'll only take a minute and save you the time (and embarressment) of asking here.

Maybe you are looking for

  • Unable to open Bootcamp install of Vista after upgrading MacBook Pro / Mid 2010 to OS Mavericks

    Dear Community, I am unable able to boot the Windows Vista install (via Boot Camp) on my MacBook Pro / mid 2010 after upgrading to OS Maverick. Any idea about how this problem can be solved (I don't want to purchase Windows 7 and I don't want to purc

  • POPUP get date - wich name ?

    Hello, I need a popup to choose a data (with matchcode). I found it 'CNEV_01_POPUP_GET_DATE' It's run ok, but I would to change the title text ... I tried to copy and modify from standard, but the text title is not modified... Any other idea ? tks, r

  • My iWeb page on Safari is a mess while on Firefox is ok...

    Hello everyone of you. I'm experiencing this crazy thing at this very moment. I'm building my new site and while on Firefox everything seems (and really is) to be ok, on Safari it's a total mess, displaying name to old links etc, instead of the real

  • SBO-Common with the DI server

    Do I need to have the DI server installed on the same machine as the SBO-Common database in order for the DI server to work?  Or can I use a DI server on a remote environment?  Thanks in advance

  • TCS Configuration in MIRO

    Hi All We have to configure TCS for buying scrape, vendor is giving scrape by adding TCS e.g 500 material Plus 50 TCS = 550 pl give me configuration steps Thanks in advance Vishvas B