博為峰小博老師:
這個程序首先創(chuàng)建一個DefaultListModel類的繼承類,然后將其實例化成兩個不同的列表框,當(dāng)雙擊左邊的列表框中的數(shù)據(jù)時,就會在右邊添加相應(yīng)的數(shù)據(jù),反之亦然。具體代碼如下:
publicclassBWFextendsMouseAdapter{
JListlist1=null;
JListlist2=null;
DefaultListModelmode1=null;
DefaultListModelmode2=null;
String[]s={"Java","C","C#","Hibernate"};
publicBWF(){
JFramejf=newJFrame("博為峰教育");
ContainercontentPane=jf.getContentPane();
contentPane.setLayout(newGridLayout(1, 2));
mode1=newDataModel(1);
list1=newJList(mode1);
list1.setBorder(BorderFactory.createTitledBorder("圖書種類!"));
list1.addMouseListener(this);
mode2=newDataModel(2);
list2=newJList(mode2);
list2.setBorder(BorderFactory.createTitledBorder("您選擇的書:"));
list2.addMouseListener(this);
contentPane.add(newJScrollPane(list1));
contentPane.add(newJScrollPane(list2));
jf.pack();
jf.setVisible(true);
jf.addWindowListener(newWindowAdapter() {
publicvoidwindowClosing(WindowEvente) {
System.exit(0);
}
});
}
publicstaticvoidmain(String[]args) {
newBWF();
}
publicvoidmouseClicked(java.awt.event.MouseEvente) {
intindex;
if(e.getSource()==list1){
if(e.getClickCount()==2){
index=list1.locationToIndex(e.getPoint());
Stringtmp=(String)mode1.getElementAt(index);
mode2.addElement(tmp);
list2.setModel(mode2);
mode1.removeElementAt(index);
list1.setModel(mode1);
}
}
if(e.getSource()==list2){
if(e.getClickCount()==2){
index=list2.locationToIndex(e.getPoint());
Stringtmp=(String)mode2.getElementAt(index);
mode1.addElement(tmp);
list1.setModel(mode1);
mode2.removeElementAt(index);
list2.setModel(mode2);
}
}
}
classDataModelextendsDefaultListModel{
DataModel(intflag) {
if(flag==1){
for(inti=0;i
addElement(s[i]);
}
}
}
}
}