Question

I'm having a little scenario here that maybe a duplicate. I have JTable where i show some data, i have a mouselistener that listens for right clicks on the table and displays a popup menu with one menuitem. My goal is that when the user clicks the menuitem, i get the values from the table and feed them into a custom dialog which has some fill in fields, so that the user doesn't have to feed the whole dialog by hand since i will feed the dialog with the values selected on the table. but my problem is that the menuitem actionevent doesn't have a way of getting the point so that i can use table.getRowAt(). i have read another comment (check here https://stackoverflow.com/a/4122082/1788917) where i have been told that i can save the row number in a variable that can then be accessed by the actionlistener for the menuitem.

i want it to look like this

theScrollPane.getViewport().add(myJTable, null);
JMenuItem menuItem = new JMenuItem(clickMe);

menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
    menuItemActionPerformed(e);
}
});

MouseListener popupListener = new PopupListener(); 
popupMenu.add(menuItem);
myJTable.addMouseListener(popupListener);

protected void menuItemActionPerformed (ActionEvent e) {
    // what to do here to get the table row data
    // and send it to my custom dialog via it's constructor ???
}


// a simple nested class for the popup
class PopupListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
        int row = myJTable.rowAtPoint(e.getPoint());
        int selectedRow = myJTable.getSelectedRow();

        // just to make sure the popup appears only where the row is 
                    // selected
        if (row == selectedRow) {
            showPopup(e);
        }
    }

    public void mouseReleased(MouseEvent e) {
        int row = myJTable.rowAtPoint(e.getPoint());
        int selectedRow = myJTable.getSelectedRow();
        if (row == selectedRow) {
            showPopup(e);
        }
    }

    private void showPopup(MouseEvent e) {
        if (e.isPopupTrigger()) {
        popupMenu.show(e.getComponent(), e.getX(), e.getY());
        }
    }

}

so my question is, is saving the row number the only way that i can do this or is there a better way?

Was it helpful?

Solution

i have read another comment (check here https://stackoverflow.com/a/4122082/1788917) where i have been told that i can save the row number in a variable

You read the wrong comment.

If you read the answer above that link (ie. the one with 7 votes) you will see the solution is to select the row you clicked on BEFORE showing the popup menu. Then in your menu item Action you can reference

table.getSelectedRow();

OTHER TIPS

I have tried your case referring to this case and I am able to get the row and show it in a JDialog. I just modified my old code to do this. I haven't thoroughly tested.

Pop Up In JTable

import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;


public class AllTableExample {


    private JTabbedPane tabbedPane;
    private JTable allTable;
    private AllTableModel allTableModel;

    public AllTableExample() {

        List<TableData> data = new ArrayList<TableData>();
        data.add(new TableData("John1", "A", "Maths", "Hellen1"));
        data.add(new TableData("John2", "A", "Maths", "Hellen2"));
        data.add(new TableData("John3", "A", "Maths", "Hellen3"));
        data.add(new TableData("John4", "A", "Maths", "Hellen4"));
        data.add(new TableData("John5", "A", "Maths", "Hellen5"));

        allTableModel = new AllTableModel(data);
    }

    public void createUI() {
        JFrame frame = new JFrame();

        tabbedPane = new JTabbedPane();

        tabbedPane.add("All", getAllTablePanel());

        frame.add(tabbedPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Table Model Example.");
        frame.pack();
        frame.setVisible(true);
    }

    private JPanel getAllTablePanel() {
        JPanel panel = new JPanel();
        allTable = new JTable(allTableModel);
        JScrollPane scroll = new JScrollPane(allTable);
        panel.add(scroll);

        allTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                int r = allTable.rowAtPoint(e.getPoint());
                if (r >= 0 && r < allTable.getRowCount()) {
                    allTable.setRowSelectionInterval(r, r);
                } else {
                    allTable.clearSelection();
                }

                int rowindex = allTable.getSelectedRow();
                if (rowindex < 0)
                    return;
                if (e.getComponent() instanceof JTable) {
                    JDialog dialog = new JDialog();
                    int selectedRow = allTable.getSelectedRow();

                    dialog.setTitle("Edit Row: " + selectedRow);

                    TableData data = ((AllTableModel) allTable.getModel()).getTableData().get(selectedRow);
                    List<TableData> tempData = new ArrayList<TableData>();
                    tempData.add(data);

                    AllTableModel tempModel = new AllTableModel(tempData);

                    JTable table = new JTable(tempModel);
                    dialog.add(new JScrollPane(table));
                    dialog.setVisible(true);
                }
            }
            });

        return panel;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new AllTableExample().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

}


class AllTableModel extends AbstractTableModel {

    List<TableData> tableData = new ArrayList<TableData>();

    Object[] columnNames = {"Name", "Grade", "Subject", "Staff"};

    public AllTableModel(List<TableData> data) {

        tableData = data;
    }

    public List<TableData> getTableData() {
        return tableData;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column].toString();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public int getRowCount() {
        return tableData.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        TableData data = tableData.get(rowIndex);
        switch (columnIndex) {
        case 0:
            return data.getName();
        case 1:
            return data.getGrade();
        case 2:
            return data.getSubject();
        case 3:
            return data.getStaff();
        default:
            return null;
        }
    }

}

class TableData {

    private String name;
    private String grade;
    private String subject;
    private String staff;

    public TableData(String name, String grade, String subject, String staff) {
        super();
        this.name = name;
        this.grade = grade;
        this.subject = subject;
        this.staff = staff;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getStaff() {
        return staff;
    }
    public void setStaff(String staff) {
        this.staff = staff;
    }
}

Note: Store the row number of the table on which the pop-up opened such that after the changes in the popup dialog we have to update the original row.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top