Ayelet
Ayelet

Reputation: 11

How do I make the main window to react to a table click

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. How can I notify the main window about the event so it can display the dialog box/popup box?

Upvotes: 0

Views: 220

Answers (3)

Jonas
Jonas

Reputation: 128837

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.

Upvotes: 1

aperkins
aperkins

Reputation: 13124

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.

Upvotes: 1

Romain Hippeau
Romain Hippeau

Reputation: 24375

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

Upvotes: 1

Related Questions