Results 1 to 20 of 20
Like Tree1Likes
  • 1 Post By jim829

Thread: Program exits even when I click no or the X button on the upper corner

  1. #1
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Program exits even when I click no or the X button on the upper corner

    Here is the snippet of code that is causing the problem
    Java Code:
    addWindowListener(new WindowAdapter()
            {
                @Override
                public void windowClosing(WindowEvent e)
                {
                    int confirm = JOptionPane.showOptionDialog(
                            VendorMachineSimulation.this,
                            "Are You Sure you want to close this application?",
                            "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == JOptionPane.YES_OPTION)
                    {
                        System.exit(0);
                    }   
                }
            });
    Here is the code in its entirety.
    Java Code:
    package vendormachinesimulation;
    
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JSpinner;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    
    import java.awt.EventQueue;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.BorderLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Insets;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    import java.io.File;
    
    import static javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE;
    
    public class VendorMachineSimulation 
    {
        private JFrame machineFrame = new JFrame("Vendor Machine");
        private JButton addProductButton = new JButton("Add products");
        private JButton showProductButton = new JButton("Show products");
        private JButton insertCoinButton = new JButton("Insert Coin");
        private JButton buyProductButton = new JButton("Buy product");
        private JButton quitButton = new JButton("Quit");
        private JLabel productName = new JLabel("Product: ");
        private JLabel costLabel = new JLabel("Cost: ");
        private JLabel quantityLabel = new JLabel("Quantity: ");
        private JTextField productDescription = new JTextField(20);
        private JTextField costField = new JTextField(20);
        private JSpinner quantity = new JSpinner();
        private JPanel mainMenu = new JPanel();
        private JLabel titleScreen = new JLabel("Welcome to my Vendor Machine Simulator");
        private JLabel menuPicture = new JLabel();
        private ImageIcon vendorPicture;
        private ImageIcon smallVendorIcon;
        
        public static void main(String[] args) 
        {
             EventQueue.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    VendorMachineSimulation v = new VendorMachineSimulation();
                }
            });
        }
    
        private VendorMachineSimulation()
        {
            checkImage();
            initComponents();
        }
        
        private void initComponents()
        {
            titleScreen.setHorizontalAlignment(SwingConstants.CENTER);
            machineFrame.getContentPane().add(BorderLayout.NORTH, titleScreen);
            
            machineFrame.setLayout(new GridBagLayout());
            mainMenu.setLayout(new GridBagLayout());
            
               
            GridBagConstraints left = new GridBagConstraints();
            GridBagConstraints right = new GridBagConstraints();
            
            right.gridheight = GridBagConstraints.REMAINDER;
            right.insets = new Insets(10,50,0,0);
           
            left.insets = new Insets(5,0,5,5);
            left.anchor = GridBagConstraints.NORTHWEST;
            
            left.gridx = 0;
            left.gridy = 0;
            
            mainMenu.add(addProductButton, left);
            
            left.gridx = 0;
            left.gridy = 1;
            
            mainMenu.add(showProductButton, left);
            
            left.gridx = 0;
            left.gridy = 2;
            
            mainMenu.add(insertCoinButton, left);
            
            left.gridx = 0;
            left.gridy = 3;
            
            mainMenu.add(buyProductButton, left);
            
            left.gridx = 0;
            left.gridy = 4;
            
            mainMenu.add(quitButton, left);
            
            menuPicture.setIcon(vendorPicture);
            machineFrame.setIconImage(smallVendorIcon.getImage());
            mainMenu.add(menuPicture, right);
            
            addProductButton.setActionCommand("Add");
            quitButton.setActionCommand("quit");
                    
            addProductButton.addActionListener(new ProcessAction());
            quitButton.addActionListener(new ProcessAction());
            
            machineFrame.addWindowListener(new WindowAdapter()
            {
                @Override
                public void windowClosing(WindowEvent e)
                {
                    int confirm = JOptionPane.showOptionDialog(
                            machineFrame,
                            "Are You Sure you want to close this application?",
                            "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == JOptionPane.YES_OPTION)
                    {
                        machineFrame.dispose();
                    }
                }
            });
            
            machineFrame.getContentPane().add(mainMenu, left);
            
            machineFrame.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            machineFrame.setResizable(false);
            machineFrame.pack();
            machineFrame.setLocationRelativeTo(null);
            machineFrame.setVisible(true);
        }
        
      private void checkImage()
      {
            vendorPicture =  new ImageIcon("fastcorp-z400-foodcourtexpress-vendingmachine.jpg");
            smallVendorIcon = new ImageIcon("vending_machine.PNG");
            File file = new File(vendorPicture.toString());
            File file2 = new File(smallVendorIcon.toString());
            
            boolean exists = file.exists();
            boolean exists2 = file2.exists();
            
            if(!exists)
            {
                JOptionPane.showMessageDialog(machineFrame, "The file " + vendorPicture.toString() + " is missing");
            }
            else if(!exists2)
            {
                JOptionPane.showMessageDialog(machineFrame, "The file " + smallVendorIcon.toString() + " is missing");
            }
            else
                JOptionPane.showMessageDialog(machineFrame, "The Program is ready to start");
      }
     
      private class ProcessAction implements ActionListener
      {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            String buttonName = e.getActionCommand();
            
            switch (buttonName) 
            {
                case "Add":
                    System.out.println("Enter the name of the product that you would like to add.");
                    break;
                case "quit":
                    int confirm = JOptionPane.showOptionDialog(
                            machineFrame,
                            "Are You Sure you want to close this application?",
                            "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == JOptionPane.YES_OPTION)
                    {
                        machineFrame.dispose();
                    }   
                    break;
            }
        }
      }
    }
    My question is why does the snippet code at the top works in the class processAction but when I add to the main class that extends JFrame, it exits regardless if I click yes, no or the x button.
    Last edited by Deathslice; 04-01-2015 at 12:19 AM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Program exits even when I click no or the X button on the upper corner

    There might be a conflict with the statement on line 131
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    I commented line 131 out, ran the program, and it still caused the same problem. Any other suggestions.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Program exits even when I click no or the X button on the upper corner

    Stick some debugging in that listener.
    If nothing else it might ensure it is actually running, and not an old version or somesuch.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Program exits even when I click no or the X button on the upper corner

    When you click the X on the JFrame you are going to exit the frame regardless of any response because you have set the EXIT_ON_CLOSE option. Change that to DO_NOTHING_ON_CLOSE. Then you can control whether to exit or not.

    And don't extend JFrame. Use a separate instance (known as composition) as it is better coding practice.

    Regards,
    Jim
    Deathslice likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  6. #6
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    Thanks Jim it worked and thanks for the heads up on to not extend JFrame. I'll do that the next times I use JFrame

  7. #7
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    Also, besides what you just said, is there anything in this program that seems superfluous or is there a way I could make *insert line of code* much easier with less lines of code? Also in both the window listener and the processAction class, should I use *name of the Jframe*.dispose() with or without the system.exit(0); ? I see that a lot when exiting any application
    Last edited by Deathslice; 03-31-2015 at 10:11 PM.

  8. #8
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    I took your advice Jim and I took out the extend javax.swing.Frame and made it one single frame and also can you please answer my previous post. Now I guess the next thing I want to do is to have the addProductbutton send the user to another frame.

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Program exits even when I click no or the X button on the upper corner

    You want to reverse the order of these statements.

    Java Code:
     machineFrame.setLocationRelativeTo(null);
     machineFrame.pack();
    Think about it. The first, centers the frame based on the current dimensions. But then, pack() may change those dimensions so the frame may be off center. So center it after you have packed it.

    Also, and it's not a big deal, but JFrame's add() method is a helper method which adds components to the contentPane. So you don't need to add to the contentPane yourself. It just saves a little typing.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  10. #10
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    Ok what I about the comment that I made about using the dipose method or system.exit(0)?

  11. #11
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    Main Menu Frame
    Java Code:
    package vendormachinesimulation;
    
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    
    import java.awt.EventQueue;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.BorderLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Insets;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    import java.io.File;
    
    import static javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE;
    
    public class VendorMachineSimulation 
    {
        private JFrame machineFrame = new JFrame("Vendor Machine");
        private JButton addProductButton = new JButton("Add products");
        private JButton showProductButton = new JButton("Show products");
        private JButton insertCoinButton = new JButton("Insert Coin");
        private JButton buyProductButton = new JButton("Buy product");
        private JButton quitButton = new JButton("Quit");
        private JPanel mainMenu = new JPanel();
        private JLabel titleScreen = new JLabel("Welcome to my Vendor Machine Simulator");
        private JLabel menuPicture = new JLabel();
        private ImageIcon vendorPicture;
        private ImageIcon smallVendorIcon;
        
        public static void main(String[] args) 
        {
             EventQueue.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    VendorMachineSimulation v = new VendorMachineSimulation();
                }
            });
        }
    
        protected VendorMachineSimulation()
        {
            checkImage();
            initComponents();
        }
        
        private void initComponents()
        {
            titleScreen.setHorizontalAlignment(SwingConstants.CENTER);
            machineFrame.getContentPane().add(BorderLayout.NORTH, titleScreen);
            
            mainMenu.setLayout(new GridBagLayout());
            
            GridBagConstraints left = new GridBagConstraints();
            GridBagConstraints right = new GridBagConstraints();
            
            right.insets = new Insets(10,50,0,0);
            right.gridheight = GridBagConstraints.REMAINDER;
           
            left.insets = new Insets(5,0,5,5);
            left.anchor = GridBagConstraints.NORTHWEST;
            
            left.gridx = 0;
            left.gridy = 0;
            
            mainMenu.add(addProductButton, left);
            
            left.gridx = 0;
            left.gridy = 1;
            
            mainMenu.add(showProductButton, left);
            
            left.gridx = 0;
            left.gridy = 2;
            
            mainMenu.add(insertCoinButton, left);
            
            left.gridx = 0;
            left.gridy = 3;
            
            mainMenu.add(buyProductButton, left);
            
            left.gridx = 0;
            left.gridy = 4;
            
            mainMenu.add(quitButton, left);
            
            menuPicture.setIcon(vendorPicture);
            machineFrame.setIconImage(smallVendorIcon.getImage());
            mainMenu.add(menuPicture, right);
            
            addProductButton.setActionCommand("Add");
            quitButton.setActionCommand("quit");
                    
            addProductButton.addActionListener(new ProcessAction());
            quitButton.addActionListener(new ProcessAction());
            
            machineFrame.addWindowListener(new WindowAdapter()
            {
                @Override
                public void windowClosing(WindowEvent e)
                {
                    int confirm = JOptionPane.showOptionDialog(
                            machineFrame,
                            "Are You Sure you want to close this application?",
                            "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == JOptionPane.YES_OPTION)
                    {
                        machineFrame.dispose();
                    }
                }
            });
            
            machineFrame.getContentPane().add(BorderLayout.CENTER, mainMenu);
            
            machineFrame.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            machineFrame.pack();
            machineFrame.setMinimumSize(machineFrame.getPreferredSize());
            machineFrame.setLocationRelativeTo(null);
            machineFrame.setVisible(true);
        }
        
      private void checkImage()
      {
            vendorPicture =  new ImageIcon("fastcorp-z400-foodcourtexpress-vendingmachine.jpg");
            smallVendorIcon = new ImageIcon("vending_machine.PNG");
            File file = new File(vendorPicture.toString());
            File file2 = new File(smallVendorIcon.toString());
            
            boolean exists = file.exists();
            boolean exists2 = file2.exists();
            
            if(!exists)
            {
                JOptionPane.showMessageDialog(machineFrame, "The file " + vendorPicture.toString() + " is missing");
                machineFrame.dispose();
            }
            else if(!exists2)
            {
                JOptionPane.showMessageDialog(machineFrame, "The file " + smallVendorIcon.toString() + " is missing");
                machineFrame.dispose();
            }
      }
     
      private class ProcessAction implements ActionListener
      {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            String buttonName = e.getActionCommand();
            
            switch (buttonName) 
            {
                case "Add":
                    AddProduct product = new AddProduct();
                    break;
                case "quit":
                    int confirm = JOptionPane.showOptionDialog(
                            machineFrame,
                            "Are You Sure you want to close this application?",
                            "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == JOptionPane.YES_OPTION)
                    {
                        machineFrame.dispose();
                    }   
                    break;
            }
        }
      }
    }

    addProductFrame
    Java Code:
    package vendormachinesimulation;
    
    import java.awt.BorderLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JSpinner;
    import javax.swing.JTextField;
    import javax.swing.SpinnerModel;
    import javax.swing.SpinnerNumberModel;
    
    import static javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE;
    
    public class AddProduct 
    {
        private JFrame addProductFrame = new JFrame("Add a product to the inventory");
        private JPanel addProductPanel = new JPanel();
        private JLabel productName = new JLabel("Enter product description: ");
        private JLabel costLabel = new JLabel("Cost of the product: ");
        private JLabel quantityLabel = new JLabel("Quantity: ");
        private JTextField productDescription = new JTextField(20);
        private JTextField costField = new JTextField(20);
        private SpinnerModel model = new SpinnerNumberModel(1,1,10,1);
        private JSpinner quantity = new JSpinner(model);
        private JButton enterButton = new JButton("Enter");
        private JButton returnToTheMainMenu = new JButton("Return to the main menu");
        private ImageIcon smallVendorIcon = new ImageIcon("vending_machine.PNG");
        
        protected AddProduct()
        {
            initComponents();
        }
        
        private void initComponents()
        {
             addProductPanel.setLayout(new GridBagLayout());
            
             GridBagConstraints left = new GridBagConstraints();
             GridBagConstraints right = new GridBagConstraints();
             GridBagConstraints bottom = new GridBagConstraints();
             GridBagConstraints southEast = new GridBagConstraints();
             
             left.anchor = GridBagConstraints.WEST;
             left.fill = GridBagConstraints.NONE;
             
             right.fill = GridBagConstraints.HORIZONTAL;
             right.anchor = GridBagConstraints.EAST;
             
             bottom.insets = new Insets(5,0,0,0);
             bottom.fill = GridBagConstraints.NONE;
             bottom.anchor = GridBagConstraints.SOUTH;
             
             southEast.insets = new Insets(5,0,0,0);
             southEast.fill = GridBagConstraints.NONE;
             southEast.anchor = GridBagConstraints.SOUTHEAST;
             
             left.gridx = 0;
             left.gridy = 0;
             
             addProductPanel.add(productName, left);
             
             left.gridx = 0;
             left.gridy = 1;
             
             addProductPanel.add(costLabel, left);
             
             left.gridx = 0;
             left.gridy = 2;
             
             addProductPanel.add(quantityLabel, left);
             
             right.gridx = 1;
             right.gridy = 0;
             
             addProductPanel.add(productDescription, right);
             
             right.gridx = 1;
             right.gridy = 1;
             
             addProductPanel.add(costField, right);
             
             right.gridx = 1;
             right.gridy = 2;
             
             addProductPanel.add(quantity, right);
             
             bottom.gridx = 1;
             bottom.gridy = 3;
             
             addProductPanel.add(enterButton, bottom);
             
             southEast.gridx = 2;
             southEast.gridy = 3;
             
             addProductPanel.add(returnToTheMainMenu, southEast);
             
             productDescription.setEditable(true);
             costField.setEditable(true);
             quantity.setEditor(new JSpinner.DefaultEditor(quantity));
             
             quantity.addChangeListener(new ChangeListener() 
             {
                        @Override
                        public void stateChanged(ChangeEvent e) 
                        {
                            int val = (int)quantity.getValue();
                        }
             });
           
             addProductFrame.addWindowListener(new WindowAdapter()
            {
                @Override
                public void windowClosing(WindowEvent e)
                {
                    int confirm = JOptionPane.showOptionDialog(
                            addProductFrame,
                            "Are You Sure you want to close this window?",
                            "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == JOptionPane.YES_OPTION)
                    {
                        addProductFrame.dispose();
                    }
                }
            });
             
             costField.addKeyListener(new KeyAdapter()
             {
                   @Override
                   public void keyTyped(KeyEvent e)
                   {
                       char c = e.getKeyChar();
                       
                       if(!(Character.isDigit(c)) && !(Character.isSpaceChar(c)) && !(c==KeyEvent.VK_BACK_SPACE) && !(c==KeyEvent.VK_DELETE) && !(c== ','))
                       {
                           addProductFrame.getToolkit().beep();
                           e.consume();
                       }
                   }
             });
             
             productDescription.addKeyListener(new KeyAdapter()
             {
                   @Override
                   public void keyTyped(KeyEvent e)
                   {
                       char c = e.getKeyChar();
                       
                       if(!(Character.isLetter(c)) && !(Character.isSpaceChar(c)) && !(c==KeyEvent.VK_BACK_SPACE) && !(c==KeyEvent.VK_DELETE) && !(c== ',') && !(c== 39))
                       {
                           addProductFrame.getToolkit().beep();
                           e.consume();
                       }
                   }
             });
             
             returnToTheMainMenu.setActionCommand("return");
             returnToTheMainMenu.addActionListener(new ProcessAction());
             
             addProductFrame.setIconImage(smallVendorIcon.getImage());
             addProductFrame.add(BorderLayout.CENTER, addProductPanel);
             
             addProductFrame.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
             addProductFrame.pack();
             addProductFrame.setMinimumSize(addProductFrame.getPreferredSize());
             addProductFrame.setLocationRelativeTo(null);
             addProductFrame.setVisible(true);
        }
        
      private class ProcessAction implements ActionListener
      {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            String buttonName = e.getActionCommand();
            
            switch (buttonName) 
            {
                case "return":
                    int confirm = JOptionPane.showOptionDialog(
                            addProductFrame,
                            "Are You Sure you want to return to the main menu?",
                            "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == JOptionPane.YES_OPTION)
                    {
                        addProductFrame.dispose();
                    }   
                    break;
            }
        }
      }
    }
    This is what I've done so far compared to last time and it everything works as intended(as far as I know). What I want to do next is extract the information from the addproductFrame(the name of the product, cost and quantity from each of those fields), add to an arrayList and then display whenever the user clicks the show Product button. If you see any design flaws that are really a no-no please, feel free to comment on it.
    Last edited by Deathslice; 04-01-2015 at 07:27 PM.

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Program exits even when I click no or the X button on the upper corner

    Since you want to maintain the products the user has added then this is the point you want to make sure you keep the "business logic" separate from the display logic.
    The business logic (limited though it might be at the moment) will control the flow of data between your view and wherever your data (currently products) is stored.

    Something as simple as a ProductController, that registers itself as a listener with your view code above.
    That code will. for example when the user adds a product, inform the listener with all the relevant data.

    The ultimate goal should be to allow you to extract the business side of your code and plug it into any other type of front end.
    If nothing else it also makes it a lot easier to test.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    Main Frame
    Java Code:
    package vendormachinesimulation;
    
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    
    import java.awt.EventQueue;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.BorderLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Insets;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    import java.io.File;
    import javax.swing.JComboBox;
    import javax.swing.JSpinner;
    import javax.swing.SpinnerModel;
    import javax.swing.SpinnerNumberModel;
    
    import static javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE;
    
    public class VendorMachineSimulation 
    {
        private JFrame machineFrame = new JFrame("Vendor Machine");
        private JButton addProductButton = new JButton("Add products");
        private JButton showProductButton = new JButton("Show products");
        private JButton insertCoinButton = new JButton("Insert Coin");
        private JButton buyProductButton = new JButton("Buy product");
        private JButton quitButton = new JButton("Quit");
        private JPanel mainMenu = new JPanel();
        private JLabel titleScreen = new JLabel("Welcome to my Vendor Machine Simulator");
        private JLabel menuPicture = new JLabel();
        private SpinnerModel model = new SpinnerNumberModel(0.0, 0.0, 1.0, 0.05);
        private JSpinner coinSpinner = new JSpinner(model);
        private JSpinner.NumberEditor editor = new JSpinner.NumberEditor(coinSpinner);
        private JComboBox productList = new JComboBox();
        private double userMoney = 0;
        private double vendingMachineMoney = 0;
        private ImageIcon vendorPicture;
        private ImageIcon smallVendorIcon;
        protected AddProduct product = new AddProduct();
        
        public static void main(String[] args) 
        {
             EventQueue.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    VendorMachineSimulation v = new VendorMachineSimulation();
         
                    v.checkFiles();
                    
                    if(v.checkFiles() == true)
                    {
                        v.initComponents();
                    }
                }
            });
        }
        
        private void initComponents()
        {
            titleScreen.setHorizontalAlignment(SwingConstants.CENTER);
            machineFrame.getContentPane().add(BorderLayout.NORTH, titleScreen);
            
            mainMenu.setLayout(new GridBagLayout());
            
            GridBagConstraints left = new GridBagConstraints();
            GridBagConstraints right = new GridBagConstraints();
            
            right.insets = new Insets(10,50,0,0);
            right.gridx = 3;
            right.gridy = 0;   
            right.gridheight = GridBagConstraints.REMAINDER;
           
            left.insets = new Insets(5,0,5,5);
            left.anchor = GridBagConstraints.NORTHWEST;
            
            left.gridx = 0;
            left.gridy = 0;
            
            mainMenu.add(addProductButton, left);
            
            left.gridx = 0;
            left.gridy = 1;
            
            mainMenu.add(showProductButton, left);
            
            left.gridx = 0;
            left.gridy = 2;
            
            mainMenu.add(insertCoinButton, left);
            
            left.gridx = 0;
            left.gridy = 3;
            
            mainMenu.add(buyProductButton, left);
            
            left.gridx = 0;
            left.gridy = 4;
            
            mainMenu.add(quitButton, left);
            
            left.gridx = 1;
            left.gridy = 2;
            left.ipadx = 25;
            
            mainMenu.add(coinSpinner, left);
            
            left.gridx = 1;
            left.gridy = 3;
            left.ipadx = 75;
            left.fill = GridBagConstraints.NONE;
            
            mainMenu.add(productList, left);
            
            menuPicture.setIcon(vendorPicture);
            machineFrame.setIconImage(smallVendorIcon.getImage());
            mainMenu.add(menuPicture, right);
            
            addProductButton.setActionCommand("Add");
            quitButton.setActionCommand("quit");
            insertCoinButton.setActionCommand("insert");
            buyProductButton.setActionCommand("buy");
                    
            addProductButton.addActionListener(new ProcessAction());
            quitButton.addActionListener(new ProcessAction());
            insertCoinButton.addActionListener(new ProcessAction());
            buyProductButton.addActionListener(new ProcessAction());
            
            coinSpinner.setEditor(new JSpinner.DefaultEditor(coinSpinner));
            coinSpinner.setEditor(editor);
            coinSpinner.setEnabled(false);
            coinSpinner.setSize(coinSpinner.getPreferredSize());
            
            productList.setEnabled(false);
            productList.setSize(productList.getPreferredSize());
            productList.setPrototypeDisplayValue("Product");
            productList.addItem("Product");
            
            machineFrame.addWindowListener(new WindowAdapter()
            {
                @Override
                public void windowClosing(WindowEvent e)
                {
                    int confirm = JOptionPane.showOptionDialog(
                            machineFrame,
                            "Are You Sure you want to close this application?",
                            "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == JOptionPane.YES_OPTION)
                    {
                        machineFrame.dispose();
                    }
                }
            });
            
            machineFrame.getContentPane().add(mainMenu);
            
            machineFrame.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            machineFrame.pack();
            machineFrame.setMinimumSize(machineFrame.getPreferredSize());
            machineFrame.setLocationRelativeTo(null);
            machineFrame.setVisible(true);
        }
        
      private boolean checkFiles()
      {
            vendorPicture =  new ImageIcon("fastcorp-z400-foodcourtexpress-vendingmachine.jpg");
            smallVendorIcon = new ImageIcon("vending_machine.PNG");
            File file = new File(vendorPicture.toString());
            File file2 = new File(smallVendorIcon.toString());
            
            boolean exists = file.exists();
            boolean exists2 = file2.exists();
            
            if(!exists)
            {
                JOptionPane.showMessageDialog(machineFrame, "The file " + vendorPicture.toString() + " is missing");
                return false;
            }
            else if(!exists2)
            {
                JOptionPane.showMessageDialog(machineFrame, "The file " + smallVendorIcon.toString() + " is missing");
                return false;
            }
            
            return true;
      }
     
      private class ProcessAction implements ActionListener
      {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            String buttonName = e.getActionCommand();
            
            switch (buttonName) 
            {
                case "Add":
                    AddProduct ap = new AddProduct();
                    ap.run();
                    product = ap;
                    break;
                case "quit":
                    int confirm = JOptionPane.showOptionDialog(
                            machineFrame,
                            "Are You Sure you want to close this application?",
                            "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == JOptionPane.YES_OPTION)
                    {
                        machineFrame.dispose();
                    }   
                    break;
                case "insert":
                    if(product.checkInventory())
                    {
                        JOptionPane.showMessageDialog(mainMenu, "No Products in the vending machine.");          
                    }
                    else
                    {
                      coinSpinner.setEnabled(true);
                      vendingMachineMoney += (double)coinSpinner.getValue();
                      coinSpinner.setValue(0.0);
                    }
                    break;
                case "buy":
                    if(product.checkInventory())
                    {
                        JOptionPane.showMessageDialog(mainMenu, "No Products in the vending machine.");   
                    }
                    else
                    {
                        productList.setEnabled(true);
                        productList.removeItem("Product");
                        String tempArray[] = product.sendingInformationToVendor();
                    
                        for (String tempArray1 : tempArray) 
                        {
                            productList.addItem(tempArray1);
                        }
                    }
            }
        }
      }
    }
    addProductFrame
    Java Code:
    package vendormachinesimulation;
    
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JSpinner;
    import javax.swing.JTextField;
    import javax.swing.SpinnerModel;
    import javax.swing.SpinnerNumberModel;
    
    import static javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE;
    
    public class AddProduct {
    
        private JFrame addProductFrame = new JFrame("Add a product to the inventory");
        private JPanel addProductPanel = new JPanel();
        private JLabel productName = new JLabel("Enter product description: ");
        private JLabel costLabel = new JLabel("Cost of the product: ");
        private JLabel quantityLabel = new JLabel("Quantity: ");
        private JTextField productDescription = new JTextField(20);
        private JTextField costField = new JTextField(20);
        private SpinnerModel model = new SpinnerNumberModel(1, 1, 10, 1);
        private JSpinner quantity = new JSpinner(model);
        private JButton enterButton = new JButton("Enter");
        private JButton returnToTheMainMenu = new JButton("Return to the main menu");
        private ImageIcon smallVendorIcon = new ImageIcon("vending_machine.PNG");
        protected ProductInventory proInv = new ProductInventory();
    
        protected void run() {
            initComponents();
        }
    
        protected void initComponents() {
            addProductPanel.setLayout(new GridBagLayout());
    
            GridBagConstraints left = new GridBagConstraints();
            GridBagConstraints right = new GridBagConstraints();
            GridBagConstraints bottom = new GridBagConstraints();
            GridBagConstraints southEast = new GridBagConstraints();
    
            left.anchor = GridBagConstraints.WEST;
            left.fill = GridBagConstraints.NONE;
    
            right.fill = GridBagConstraints.HORIZONTAL;
            right.anchor = GridBagConstraints.EAST;
    
            bottom.insets = new Insets(5, 0, 0, 0);
            bottom.fill = GridBagConstraints.NONE;
            bottom.anchor = GridBagConstraints.SOUTH;
    
            southEast.insets = new Insets(5, 0, 0, 0);
            southEast.fill = GridBagConstraints.NONE;
            southEast.anchor = GridBagConstraints.SOUTHEAST;
    
            left.gridx = 0;
            left.gridy = 0;
    
            addProductPanel.add(productName, left);
    
            left.gridx = 0;
            left.gridy = 1;
    
            addProductPanel.add(costLabel, left);
    
            left.gridx = 0;
            left.gridy = 2;
    
            addProductPanel.add(quantityLabel, left);
    
            right.gridx = 1;
            right.gridy = 0;
    
            addProductPanel.add(productDescription, right);
    
            right.gridx = 1;
            right.gridy = 1;
    
            addProductPanel.add(costField, right);
    
            right.gridx = 1;
            right.gridy = 2;
    
            addProductPanel.add(quantity, right);
    
            bottom.gridx = 1;
            bottom.gridy = 3;
    
            addProductPanel.add(enterButton, bottom);
    
            southEast.gridx = 2;
            southEast.gridy = 3;
    
            addProductPanel.add(returnToTheMainMenu, southEast);
    
            productDescription.setEditable(true);
            costField.setEditable(true);
            quantity.setEditor(new JSpinner.DefaultEditor(quantity));
    
            addProductFrame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    int confirm = JOptionPane.showOptionDialog(
                            addProductFrame,
                            "Are You Sure you want to close this window?",
                            "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, null, null);
                    if (confirm == JOptionPane.YES_OPTION) {
                        addProductFrame.dispose();
                    }
                }
            });
    
            costField.addKeyListener(new KeyAdapter() {
                @Override
                public void keyTyped(KeyEvent e) {
                    char c = e.getKeyChar();
    
                    if (!(Character.isDigit(c)) && !(Character.isSpaceChar(c))
                            && !(c == KeyEvent.VK_BACK_SPACE) && !(c == KeyEvent.VK_DELETE)
                            && !(c == ',') && !(c == '.')) {
                        addProductFrame.getToolkit().beep();
                        e.consume();
                    }
                }
            });
    
            productDescription.addKeyListener(new KeyAdapter() {
                @Override
                public void keyTyped(KeyEvent e) {
                    char c = e.getKeyChar();
    
                    if (!(Character.isLetter(c)) && !(Character.isSpaceChar(c)) && !(c == KeyEvent.VK_BACK_SPACE) && !(c == KeyEvent.VK_DELETE)
                            && !(c == ',') && !(c == 39)) {
                        addProductFrame.getToolkit().beep();
                        e.consume();
                    }
                }
            });
    
            returnToTheMainMenu.setActionCommand("return");
            returnToTheMainMenu.addActionListener(new ProcessAction());
            enterButton.setActionCommand("enter");
            enterButton.addActionListener(new ProcessAction());
    
            addProductFrame.setIconImage(smallVendorIcon.getImage());
            addProductFrame.add(addProductPanel);
    
            addProductFrame.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            addProductFrame.pack();
            addProductFrame.setMinimumSize(addProductFrame.getPreferredSize());
            addProductFrame.setLocationRelativeTo(null);
            addProductFrame.setVisible(true);
        }
    
        protected boolean checkInventory() {
            return proInv.isInventoryEmpty();
        }
    
        protected String[] sendingInformationToVendor() {
            String[] array = new String[proInv.getInventorySize()];
    
            array = proInv.sendProductInformation();
    
            return array;
        }
    
        private class ProcessAction implements ActionListener {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                String buttonName = e.getActionCommand();
    
                switch (buttonName) {
                    case "enter":
                        if (productDescription.getText().equals("") || costField.getText().equals("")) {
                            JOptionPane.showMessageDialog(addProductFrame, "Filling in all the necessary fields.");
                        } else {
                            String prodName = productDescription.getText();
                            String tempProdCost = costField.getText();
                            double prodCost = Double.parseDouble(tempProdCost);
                            int q = (int) quantity.getValue();
    
                            Product p = new Product(prodName, prodCost, q);
                            proInv.addProduct(p);
                            JOptionPane.showMessageDialog(addProductFrame, "This product has been successfully added to the vending machine");
                            productDescription.setText("");
                            costField.setText("");
                            quantity.setValue(1);
                        }
                        break;
                    case "return":
                        int confirm = JOptionPane.showOptionDialog(
                                addProductFrame,
                                "Are You Sure you want to return to the main menu?",
                                "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                                JOptionPane.QUESTION_MESSAGE, null, null, null);
                        if (confirm == JOptionPane.YES_OPTION) {
                            addProductFrame.dispose();
                        }
                        break;
                }
            }
        }
    }
    product class
    Java Code:
    package vendormachinesimulation;
    
    public class Product 
    {
        private String productDescription;
        private double cost;
        private int quantity;
    
        public Product(String productDescription, double cost, int quantity) 
        {
            this.productDescription = productDescription;
            this.cost = cost;
            this.quantity = quantity;
        }
    
        public void setProductDescription(String productDescription) 
        {
            this.productDescription = productDescription;
        }
    
        public void setCost(double cost) 
        {
            this.cost = cost;
        }
    
        public void setQuantity(int quantity) 
        {
            this.quantity = quantity;
        }
    
        public String getProductDescription() 
        {
            return productDescription;
        }
    
        public double getCost() 
        {
            return cost;
        }
    
        public int getQuantity() 
        {
            return quantity;
        }
    
        @Override
        public String toString() 
        {
            return "Product: " + productDescription + "  " + " Cost: " +  cost + " " + " Quantity: " + quantity;
        }
        
          
    }
    productInventory class
    Java Code:
    package vendormachinesimulation;
    
    import java.util.ArrayList;
    
    public class ProductInventory 
    {
        private ArrayList<Product> productInventory = new ArrayList<>();
        
        protected int getInventorySize()
        {
            return productInventory.size();
        }
    
        protected boolean isInventoryEmpty()
        {
            return productInventory.isEmpty();
        }
        
        protected void addProduct(Product p)
        {
            productInventory.add(p);
        }
        
        protected String [] sendProductInformation()
        {
            String [] array = new String[productInventory.size()];
            
            for (int i = 0; i < array.length; i++) 
            {
                array[i] = productInventory.get(i).getProductDescription();
            }
            
            return array;
        }
        
        protected void removeProduct()
        {
            for(int i=0; i<productInventory.size(); i++)
            {
                if(productInventory.get(i).getQuantity() == 0)
                {
                    productInventory.remove(i);
                }
            }
        }
        
        protected String[] addToArray()
        {
            String [] array = new String[productInventory.size()];
            
            for (int i = 0; i < array.length; i++) 
            {
                array[i] = productInventory.get(i).getProductDescription();
            }
            
            return array;
        }
        
        protected void printProductInformation()
        {
            for (Product productInventory1 : productInventory) 
            {
                System.out.println(productInventory1);
            }
        }
    }

    All rights this is where I need great help because this is getting out of hand. So if someone is available for me to ask questions in case I run into other problems, I would greatly appreciate that. First a question, why does my program create one frame if a part of my program in the main frame looks this

    Java Code:
    public static void main(String[] args) 
        {
             EventQueue.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    VendorMachineSimulation v = new VendorMachineSimulation();
                    v.checkFiles();
                    
                    if(v.checkFiles() == true)
                     {
                        v.initComponents();
                     }
                }
            });
        }
    as opposed to this where it would create two main frames once the user clicks the add button
    Java Code:
    public static void main(String[] args) 
        {
             EventQueue.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    VendorMachineSimulation v = new VendorMachineSimulation();
                }
            });
        }
    
    protected VendorMachineSimulation()
    {
        v.checkFiles();
                    
       if(checkFiles() == true)
       {
            initComponents();
        }
    }
    Now my main problem. Here is the important relevant code
    Java Code:
    case "buy":
                    if(proInv.getProductInventory() == 0)
                    {
                        JOptionPane.showMessageDialog(mainMenu, "No Products in the vending machine.");   
                    }
                    else
                    {
                        productList.setEnabled(true);
                        String tempArray[] = proInv.addToArray();
                    
                        for (String tempArray1 : tempArray) 
                        {
                            productList.add(tempArray1, machineFrame);
                        }
                    }
    Whenever the user adds a product to the inventory, the size of the arraylist goes up( I have verified that it does and that it has the information entered by the user.) but proInv.getProductInventory() will always return zero no matter what. This most certainly has to do with how an object is instance of a class and that the object proInv has no information on the size of the arrayList going higher than zero. How would I be able to fix this given the way I structured my code(What I mean is how it do looks, all of the implementations that I've done so far etc)
    Last edited by Deathslice; 04-03-2015 at 03:04 AM.

  14. #14
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    Hurray I solved one my problems. I'll post my solution soon

  15. #15
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    As of now, the two main problems that I've addressed above have been resolved but now there is a new problem(There is no end to this mayhem). This problems occur when I add a product to the inventory, exit that frame, try to add another product but the information from the last time is still on the textfield. Worse, I have to exit twice if I try to add a product and the information doesn't get added to combobox. This is going to drive me insane.

  16. #16
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    I just don't understand. Why does the information the I enter in the Jlabel in the addProductFrame remain there when I exit the frame. If I dispose the frame, shouldn't it delete everything single bit of information that it has? Please I need help.

  17. #17
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    Anyone has any ideas because I'm really stumped on this part.

  18. #18
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    alright I've solved 2 other problems(whether or not it's a good solution is up to you). I'll add the solutions soon.

  19. #19
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    Now here is another problem that I want to solve. The only way for the frame to be updated with new information is to press a certain button(the buy button will update the JcomboBox) so it then can be re-updated with new information. I don't want that. I want the frame to be re-updated dynamically as soon as the user sends the information.

  20. #20
    Deathslice is offline Member
    Join Date
    Jan 2015
    Location
    Miami, FL
    Posts
    86
    Rep Power
    0

    Default Re: Program exits even when I click no or the X button on the upper corner

    Alright I've updated my code with my new code.

Similar Threads

  1. Why won't Eclipse let me put button in corner?
    By yahpeter in forum Android
    Replies: 2
    Last Post: 01-27-2014, 11:50 AM
  2. Replies: 1
    Last Post: 04-27-2012, 03:47 AM
  3. return value on a button click
    By wotupduck in forum New To Java
    Replies: 1
    Last Post: 03-24-2011, 01:09 PM
  4. Replies: 6
    Last Post: 12-09-2010, 08:44 AM
  5. Payroll Program exits at wrong time
    By jsand2 in forum Java Applets
    Replies: 13
    Last Post: 01-26-2009, 03:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •