21 tháng 11 2006

Swing: How to show JPopupMenu on Empty JTable ?

Swing: How to show JPopupMenu on Empty JTable ?

At 7:03 PM on Sep 15, 2005, Santhosh Kumar T DeveloperZone Top 100 wrote:

It looks like as simple as writing a MouseListener implementation and register with JTable where the MouseListener implementation shows JPopupMenu.

But this doesn't works if there are no rows in JTable. Why so? The height of the JTable is zero when there are no rows, Thus the area where user clicks is not JTable, it is JViewPort.

This can be solved by overriding the method getScrollableTracksViewportHeight () of Scrollable interface. JTable already implements Scrollable interface. So we just override that method and make the table height same as that of view-port if its preferred size is smaller than view-port size

JTable table = new JTable(0, 5){
public boolean getScrollableTracksViewportHeight() {
return getPreferredSize().height < getParent().getHeight();
}
};
This is how JTextComponent handles this. You can checkout JTextComponent.java and see getScrollableTracksViewportHeight() implementation.

Any JComponent can be scrollable by adding to JScrollable. Then what is Scrollable interface is for ? Scrollable interface which gives some hints to perform better scrolling, such as how many pixels to move per mouse-click or page up or page down.



The demo contains two tables. and both tables have the same MouseListener registered. But only the bottom table shows JPopupMenu on right mouse click. The bottom table overrides getScrollableTracksViewportHeight() as explained above.

Không có nhận xét nào: