tags:

views:

30

answers:

3

I am a new user of Java swing. I need to be able to create a popup with row info when the user clicks on that row. I managed to incorporate the mouseClick event reaction in my table class, and I have the row info available. But I don't know how to notify the main window about the event so it can display the dialog box/popup box. Can you help me?

+1  A: 

Just call a method on the main window to perform the action

Romain Hippeau
+1  A: 

There are several ways to handle this:

1) You can have the custom table class have a custom listener on it (Observer Pattern) which it then calls whenever the click occurs

2) You can have the table call a method on the main window - i.e. pass in the main window as part of the construction of the table

3) You can have the main Window register as a listener to the table (i.e. a mouse listener) and have it handle the events instead.

There are others, I am sure. These are the ones I have seen most often used. Depending on the size, scope and intent of the software being written, each has it's merits and detriments. Is this a project for school, a toy being written to learn about Swing, or is it designed to be a longer term, larger project? If it is the latter, I would recommend looking up Model View Controller (MVC) architecture discussions, as it can make, long term, the maintenance of the code much easier, in my experience.

Good luck.

aperkins
Thank you very much for your hints. I used the second idea, though I couldn't send the window in the table constructor (it doesn't allow it in static functions such as main). I sent instead the class that handles all the data uploading and editing which is a member of my main window. And it works...
Ayelet
@Ayelet: just as a point of note: it is considered good etiquette on the site to select as answered if someone answered your question. Glad I could help with your problem.
aperkins
+1  A: 

You can do it like this:

myTable.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent e) {
            if(SwingUtilities.isRightMouseButton(e)) {
                int index = myTable.rowAtPoint(e.getPoint());
                JPopupMenu popup = new JPopupMenu();
                popup.add(myMenuAction);
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }
});

And then implement an Action myMenuAction where you use the index from your table.

Jonas