user1059708
user1059708

Reputation: 1

Keeping tracks of what object triggers a common event

I have a common event handler for a set of submenus, say something like 4 menus, and 4 submenus in each. What I want is to keep track of how many times each submenu is clicked and for that I'm using an integer array as a counter for each submenu(declared with application scope), in the main class. I need to write the values in this array to a file after the GUI exits. How (and more importantly where in the code) do I do this? My array is obviously of size 16 and needs to be initialised to zero(again where do I do this?) I'm new to Java but I'm guessing I need to do something with this,

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

Upvotes: 0

Views: 48

Answers (3)

JB Nizet
JB Nizet

Reputation: 691785

First, in the class that initializes the menu items, you need to declare an array of integers. Those will be initialized to 0 automatically:

private int[] counters = new int[16];

Then, each time you initialize a menu item, you must add a listener to the item that increments the appropriate counters element:

private class CounterIncrementActionListener implements ActionListener {
    private int index;

    private CounterIncrementActionListener(int index) {
        this.index = index;
    }

    @Override 
    public void actionPerformed(ActionEvent e) {
        counters[index] = counters[index] + 1;
    }
}

...
firstItem.addActionListener(new CounterIncrementActionListener(0));
secondItem.addActionListener(new CounterIncrementActionListener(1));
...

Now, to be able to save the counters array to a file when the frame is closed, you need to add a window listener to the frame:

frame.addWindowListener(new WindowAdapter() {

    @Override
    public void windowClosing(WindowEvent e) {
        saveCounters();
        System.exit(0);
    }
}

Upvotes: 1

gotomanners
gotomanners

Reputation: 7926

Mostly from Oracle - How to Write Window Listeners

  • You need to use setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)
  • you need to add a windowListener
  • You need to override the windowClosing() method of the windowListener

e.g:

this.addWindowListener(new java.awt.event.WindowAdapter() {
   public void windowClosing(java.awt.event.WindowEvent e) {
     //Save your Array here
   }
});

Upvotes: 0

Thom
Thom

Reputation: 15052

Pass it in to the event. Many GUIs have an ActionCommand type property that you can tag with whatever string you want. You can use that to pass the information into your event.

Upvotes: 0

Related Questions