JTable Right click popupmenu in Netbeans

I want to add a popup menu with the right mouse button in a JTable in NetBeans IDE (it seems like a simple task ... lol)

I got part of the job

  • adding popupmenu to the form
  • adding menu items to popupmenu
  • go to JTable properties
  • click binding tab
  • set the value of ComponentPopupMenu to my popupmenu

But this only partly works. Now, when I right-click on a table, a menu appears, but the selected row in JTable does not change. Thus, when the actionPerformed menuitem element is called, I have no idea which line in JTable was clicked.

How can i get this? or is there an easier way to do this in netbeans?

I know there are other ways to do this (in code), but I would prefer to use the netbeans GUI builder.

Has anyone ever done this before?

Thanks for your help!

+4
source share
2 answers

Why do you rely on the IDE to generate code for you? What happens when you switch to a different IDE and you need to learn how to do this for this ideal? Learn how to write your own code, and then the IDE doesn't matter:

table.addMouseListener( new MouseAdapter() { public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { JTable source = (JTable)e.getSource(); int row = source.rowAtPoint( e.getPoint() ); int column = source.columnAtPoint( e.getPoint() ); if (! source.isRowSelected(row)) source.changeSelection(row, column, false, false); popup.show(e.getComponent(), e.getX(), e.getY()); } } }); 
+10
source

Hope I can answer this Netbeans ... and hope this helps someone

  • adding popupmenu to the form (it goes in other components) calls it For example, jPopupMenu
  • adding menu items to popupmenu
  • go to JTable functions (e.g. call jTableDataOrSomething)
  • click the anchor link (or right-click jTable Bind> items)
  • set ComponentPopupMenu to my jPopupMenu name

    Next steps,

  • while in the properties select "Events" and "mouse", set it to your jTableDataOrSomething (or right-click on the table, "Events"> "Mouse"> "Mouse")

    Netbeans creates an empty function and sets the following code

     private void jTableDataOrSomethingMouseReleased(java.awt.event.MouseEvent evt) { if (evt.isPopupTrigger()) { JTable source = (JTable)evt.getSource(); int row = source.rowAtPoint( evt.getPoint() ); int column = source.columnAtPoint( evt.getPoint() ); if (!source.isRowSelected(row)) { source.changeSelection(row, column, false, false); } jPopupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); } } 
  • create a menuitem action performed for an EACH element

    Then you can use:

      int[] rows = jTableDataOrSomething.getSelectedRows(); for (int row : rows) { boolean j = true; try { modelRow = jTableDataOrSomething.convertRowIndexToModel(row); //do something with the selected rows... 

This requires multirow selection and considers sorting / filtering.

End the function with

  jTableDataOrSomething.repaint(); 

Enjoy

0
source

Source: https://habr.com/ru/post/1315583/


All Articles