Import java. AWT. borderlayout;
Import java. AWT. event. mouseadapter;
Import java. AWT. event. mouseevent;
Import javax. Swing. defaultlistmodel;
Import javax. Swing. jframe;
Import javax. Swing. jlist;
Import javax. Swing. jmenuitem;
Import javax. Swing. jpanel;
Import javax. Swing. jpopupmenu;
Import javax. Swing. jscrollpane;
Public class jlisttest extends jframe {
Jpopupmenu popupmenu = NULL;
Jlist list = NULL;
Jpanel mainpanel = NULL;
Jscrollpane scrollpane = NULL;
Public jlisttest (){
Initcomponent ();
Setsize (200,300 );
Setdefaclocloseoperation (jframe. exit_on_close );
Setlocationrelativeto (null );
Setvisible (true );
}
Private void initcomponent (){
Mainpanel = new jpanel ();
Scrollpane = new jscrollpane ();
Popupmenu = new jpopupmenu ();
Popupmenu. Add (New jmenuitem ("open"); // Add a menu item open
Popupmenu. Add (New jmenuitem ("save "));
Mainpanel. setlayout (New borderlayout ());
List = new jlist ();
List. setmodel (New defaultlistmodel ());
List. addmouselistener (New mouseadapter (){
@ Override
Public void mouseclicked (mouseevent e ){
// Maybeshowpopup (E );
}
@ Override
Public void mousepressed (mouseevent e ){
List. setselectedindex (list. locationtoindex (E. getpoint (); // get the item clicked by the mouse
Maybeshowpopup (E );
}
@ override
Public void mousereleased (mouseevent e) {
maybeshowpopup (E );
}< br> // menu
private void maybeshowpopup (mouseevent e) {
If (E. ispopuptrigger () & list. getselectedindex ()! =-1) {
// obtain the value of the selected item
object selected = List. getModel (). getelementat (list. getselectedindex ();
system. out. println (selected);
popupmenu. show (E. getcomponent (), E. getx (), E. gety ();
}< BR >}
});
List. setlistdata (new object [] {"name", "Age", "sex", "name", "Age ",
"Name", "Age", "name", "Age "});
Scrollpane. setviewportview (list );
Mainpanel. Add (scrollpane, borderlayout. center );
This. Add (mainpanel );
}
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
New jlisttest ();
}
}