Tuesday, 30 April 2013

MDI Interface in java swing

Coming soon....

Adding context menu to jtable example



  • To add context menu you need to add mouse listener on jtable...
jTable1.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) 
        {
            int r = jTable1.rowAtPoint(e.getPoint());
            if (r >= 0 && r < jTable1.getRowCount()) {
                jTable1.setRowSelectionInterval(r, r);
            } else {
                jTable1.clearSelection();
            }
            
            //row index is found...
            int rowindex = jTable1.getSelectedRow();
            if (rowindex < 0)
                return;
            if (e.isPopupTrigger() && e.getComponent() instanceof JTable ) {
                JPopupMenu popup = createYourPopUp(rowindex,jTable1);
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }
            
    });

//here we are creating popup menu on right click of each row....
public static JPopupMenu createYourPopUp(int rowindex, JTable jTable1)
    {
         JPopupMenu popup=new JPopupMenu();
         edit=new JMenuItem("Edit Details");      
         delete=new JMenuItem("Delete Details");
         popup.add(edit);
         popup.add(delete);
        return popup;
  }

Screenshots :



Download example :
Download




How to use display member & value member in JComboBox in java


           Some times you need when you select anything from JComboBox you want to pass different information (like id of that think), so I will show you this :

Step 1) Create Model for JComboBox.


public class DisplayValueModel 
{
    public Object displayMember;
    public Object valueMember;
    
    public DisplayValueModel(Object display,Object value)
    {
        displayMember=display;
        valueMember=value;
    }
    
    public String toString()
    {
        return displayMember.toString();
    }
}

   This will hold both display member & value member for JComboBox...
   Here toString() method must be overriden, because it will decide what to display in JComboBox.

Step  2) Now in java file add directly the object of model to JComboBox

And that's it.....

Screenshot :



You can download the example :
Download