3

I am currently working on a simulated stock market for my Software Engineering class. I am using the actionlistener to open up new windows for each one of my current menu items. However, it seems that I can only use one ActionListener per class so I can only have one set window for all of my menu options. Is there any other way to implement multiple action listeners? Is there another way to do this.

Here is my code:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.BevelBorder;
    import javax.swing.table.DefaultTableModel;

    public class GUIroughdraft implements Runnable, ActionListener
    {
          private JFrame frame;
          private JMenuBar menuBar;
          private JMenu FileMenu;
          private JMenu ActionMenu;
          private JMenu HelpMenu;
          private JMenuItem SaveMenuItem;
          private JMenuItem LoadMenuItem;
          private JMenuItem ExitMenuItem;
          private JMenuItem BuyMenuItem;
          private JMenuItem SellMenuItem;
          private JMenuItem AboutMenuItem;
          private JMenuItem UserManualMenuItem;


          public static void main(String[] args)
          {
            // needed on mac os x
            System.setProperty("apple.laf.useScreenMenuBar", "true");

            // the proper way to show a jframe (invokeLater)
            SwingUtilities.invokeLater(new GUIroughdraft());
          }


        private JFrame frmBgszStockSimulator;
        /**
         * @wbp.nonvisual location=53,14
         */
        //private final JLabel lblBgszStockSimulator =                 DefaultComponentFactory.getInstance().createTitle("BGSZ Stock Simulator");
        private JTextField searchBar;
        private JTable table;

        /**
         * Launch the application. Testing Comment
         */

        /*
        public static void main(String[] args) 
        {
            EventQueue.invokeLater(new Runnable() 
            {
                public void run() 
                {
                    try 
                    {
                        GUIroughdraft window = new GUIroughdraft();
                        window.frmBgszStockSimulator.setVisible(true);
                    } catch (Exception e) 
                    {
                e.printStackTrace();
                    }
                }
            });
        }
        */



        /**
         * Create the application.
         */
        /*
        public GUIroughdraft() 
        {
            run();
        }
        */

/**
 * Initialize the contents of the frame.
 */
public void run() 
{
    frmBgszStockSimulator = new JFrame("BGSZ Stock Simulator");
    frmBgszStockSimulator.getContentPane().setBackground(Color.GRAY);
    frmBgszStockSimulator.setTitle("BGSZ Stock Simulator");
    frmBgszStockSimulator.setBounds(100, 100, 775, 510);
    frmBgszStockSimulator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmBgszStockSimulator.setVisible(true); 

    //Builds menu bar
    menuBar = new JMenuBar();

    //Builds the File menu
    FileMenu = new JMenu("File");
    SaveMenuItem = new JMenuItem("Save");
    LoadMenuItem = new JMenuItem("Load");
    ExitMenuItem = new JMenuItem("Exit");
    SaveMenuItem.addActionListener(this);
    LoadMenuItem.addActionListener(this);
    ExitMenuItem.addActionListener(this);
    FileMenu.add(SaveMenuItem);
    FileMenu.add(LoadMenuItem);
    FileMenu.add(ExitMenuItem);

    //Builds the Actions menu
    ActionMenu = new JMenu("Actions");
    BuyMenuItem = new JMenuItem("Buy");
    SellMenuItem = new JMenuItem("Sell");
    ActionMenu.add(BuyMenuItem);
    ActionMenu.add(SellMenuItem);

    //Builds the Help menu
    HelpMenu = new JMenu("Help");
    AboutMenuItem = new JMenuItem("About");
    UserManualMenuItem = new JMenuItem("User Manual");
    HelpMenu.add(AboutMenuItem);
    HelpMenu.add(UserManualMenuItem);

    menuBar.add(FileMenu);
    menuBar.add(ActionMenu);
    menuBar.add(HelpMenu);

    frmBgszStockSimulator.setJMenuBar(menuBar);


    JScrollBar scrollBar = new JScrollBar();
    scrollBar.setBackground(Color.LIGHT_GRAY);
    scrollBar.setBounds(323, 47, 21, 317);
    frmBgszStockSimulator.getContentPane().add(scrollBar);

    JTextArea displayBox = new JTextArea();
    displayBox.setEditable(false);
    displayBox.setLineWrap(true);
    displayBox.setWrapStyleWord(true);
    displayBox.setText("This will be a text field that displays all your actions and information about stocks, purchases, sales, errors, etc.");

    //when the user clicks the search button that is not there anymore 
    //create a new instance of the getStockData class
    //get the data from the input line something like  String userInput = searchBar.getText()
    //pass that to the getData(userInput);
    //set the displayBox.setText(the return from getData());

    displayBox.setBounds(12, 47, 312, 317);
    frmBgszStockSimulator.getContentPane().add(displayBox);

    searchBar = new JTextField();
    searchBar.setText("Enter your text here");
    searchBar.setBounds(12, 377, 733, 22);
    frmBgszStockSimulator.getContentPane().add(searchBar);
    searchBar.setColumns(10);

    JProgressBar progressBar = new JProgressBar();
    progressBar.setStringPainted(true);
    progressBar.setValue(75);
    progressBar.setBounds(78, 412, 586, 14);
    frmBgszStockSimulator.getContentPane().add(progressBar);

    table = new JTable();
    table.setModel(new DefaultTableModel(
            new Object[][] {
                {"Stock Name", "Stock Value", "Amount Owned", "Total Value"},
                {" BAC", "$13.48", "4", "$53.92"},
                {" RIG", "$8.89", "0", "$0.00"},
                {" SUNE", "$0.59", "12", "$7.08"},
                {" FCX", "$10.29", "2", "$20.58"},
                {" PBR", "$5.86", "0", "$0.00"},
                {" GE", "$31.83", "0", "$0.00"},
                {" VALE", "$4.24", "24", "$101.76"},
                {" VRX", "$27.07", "0", "$0.00"},
                {" PFE", "$30.07", "0", "$0.00"},
                {" CRC", "$1.05", "8", "$8.40"},
                {" GGB", "$1.82", "0", "$0.00"},
                {" CHK", "$4.01", "6", "$24.06"},
                {" T", "$39.37", "0", "$0.00"},
                {" F", "$13.35", "5", "$66.75"},
                {" WLL", "$7.66", "0", "$0.00"},
            },
            new String[] {
                "New column", "New column", "New column", "New column"
            }
        ));
    table.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
    table.setBounds(350, 51, 395, 313);
    frmBgszStockSimulator.getContentPane().add(table);

    JTextArea txtrValue = new JTextArea();
    txtrValue.setText("Displays Cash Value");
    txtrValue.setLineWrap(true);
    txtrValue.setEditable(false);
    txtrValue.setBounds(99, 12, 172, 22);
    frmBgszStockSimulator.getContentPane().add(txtrValue);

    JTextArea txtrCurrentPortfolioValue = new JTextArea();
    txtrCurrentPortfolioValue.setText("Display Portfolio Value");
    txtrCurrentPortfolioValue.setLineWrap(true);
    txtrCurrentPortfolioValue.setEditable(false);
    txtrCurrentPortfolioValue.setBounds(376, 12, 206, 22);
    frmBgszStockSimulator.getContentPane().add(txtrCurrentPortfolioValue);

    JLabel lblCashValue = new JLabel("Cash Value:");
    lblCashValue.setBounds(24, 15, 111, 16);
    frmBgszStockSimulator.getContentPane().add(lblCashValue);

    JLabel lblPortfolioValue = new JLabel("Portfolio Value:");
    lblPortfolioValue.setBounds(283, 15, 123, 16);
    frmBgszStockSimulator.getContentPane().add(lblPortfolioValue);

}

public void actionPerformed(ActionEvent ev)
  {
    SaveDialog dialog = new SaveDialog();
    dialog.setModal(true);
    dialog.setVisible(true);
  }


private class SaveDialog extends JDialog implements ActionListener
  {
    private JButton okButton = new JButton("Your File has been saved!");

    private SaveDialog()
    {
      super(frame, "Save", true);
      JPanel panel = new JPanel(new FlowLayout());
      panel.add(okButton);
      getContentPane().add(panel);
      okButton.addActionListener(this);
      setPreferredSize(new Dimension(250, 75));
      pack();
      setLocationRelativeTo(frame);
    }

    public void actionPerformed(ActionEvent ev)
    {
      setVisible(false);
    }
  }

public void actionPerformed2(ActionEvent ev)
  {
    LoadDialog dialog = new LoadDialog();
    dialog.setModal(true);
    dialog.setVisible(true);
  }

private class LoadDialog extends JDialog implements ActionListener
  {
    private JButton LoadButton = new JButton("Your File has successfully loaded!");

    private LoadDialog()
    {
      super(frame, "Load", true);
      JPanel panel = new JPanel(new FlowLayout());
      panel.add(LoadButton);
      getContentPane().add(panel);
      LoadButton.addActionListener(this);
      setPreferredSize(new Dimension(250, 75));
      pack();
      setLocationRelativeTo(frame);
    }

    public void actionPerformed(ActionEvent ev)
    {
      setVisible(false);
    }
  }


}
Scott S
  • 33
  • 1
  • 5
  • Yes you can just simply do... `comp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {// put code here and stuff} });` – 3kings Apr 12 '16 at 23:40
  • 1
    [How to Use Actions](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html) and [How to Use CardLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html) for replacing multiple windows. You might even be able to use a `JDesktopPane` instead, see [How to Use Internal Frames](https://docs.oracle.com/javase/tutorial/uiswing/components/internalframe.html) for more details – MadProgrammer Apr 12 '16 at 23:43
  • @3kings What If what I am trying to do involves creating windows in JPane inside the Action Listener. I tried what you say to do but it did not work. – Scott S Apr 13 '16 at 00:14
  • 1
    @AndrewThompson I fixed the hanging bracket error – Scott S Apr 13 '16 at 00:15
  • For [example](http://stackoverflow.com/a/4039359/230513). – trashgod Apr 13 '16 at 02:11

2 Answers2

1

You don't need to implement the ActionListener interface, instead, create anonymous classes that provide the different functionality you need for any JButton or other object. An example would look like this:

myButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // do whatever you want in here
            }

        });
djs
  • 3,947
  • 3
  • 14
  • 28
  • I will try this out to see if it works and get back to you. Thank you for answering my question, greatly appreciated. – Scott S Apr 13 '16 at 06:44
1

In GUIroughdraft class, place this code inside actionPerformed method

public void actionPerformed(ActionEvent ev)
  {
    if(ev.getActionCommand().equalsIgnoreCase("Save"){
       SaveDialog dialog = new SaveDialog();
       dialog.setModal(true);
       dialog.setVisible(true);
     }
    else if(ev.getActionCommand().equalsIgnoreCase("Load")){
         LoadDialog dialog = new LoadDialog();
         dialog.setModal(true);
         dialog.setVisible(true);
     }
    else if(ev.getActionCommand().equalsIgnoreCase("Exit")){
        // Do whatever you like
     }

  }

And also as per coding standards variable names should start with lower case letter.

private JMenuItem SaveMenuItem; ---wrong

private JMenuItem saveMenuItem; ---correct

Kiran Rajam
  • 186
  • 5
  • Alright. Sorry, it has been awhile since I have coded in Java. I will try this out and get back to you. Thanks for all of your help – Scott S Apr 13 '16 at 12:53
  • I tried using the code you provided, however, I still get the same saveDialog even when I click on the load menu item from my menu bar. Is it how I have something defined in my code? Could it possibly be on of my methods causing this conflict? – Scott S Apr 13 '16 at 14:15
  • Okay add this line as a first statement in actionPerformed method, System.out.println(ev.getActionCommand()); When you click Save it should print Save, when you click Load it should print Load. – Kiran Rajam Apr 13 '16 at 17:45