第二篇学习笔记
学习的组件的使用方法是:列表框(JList)
package proj3;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class demoJList {
JFrame mainframe;
Container con;
JButton addbtn,delbtn;
JList orignlist,destlist;
DefaultListModel orignmodel,destmodel;
JScrollPane leftjspane,rightjspane;
JSplitPane basesplitpane;
JPanel pane;
static final String msg[] = {"北京","上海","天津","辽宁","吉林","四川","海南","湖北","广东"};
public demoJList(){
mainframe = new JFrame();
con = mainframe.getContentPane();
orignmodel = new DefaultListModel();
for(int i=0;i<msg.length;i++)
orignmodel.addElement(msg[i]);
orignlist = new JList(orignmodel);
destmodel = new DefaultListModel();
destlist = new JList(destmodel);
leftjspane = new JScrollPane(orignlist);
rightjspane = new JScrollPane(destlist);
basesplitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,leftjspane,rightjspane);
con.add(basesplitpane,BorderLayout.CENTER);
addbtn = new JButton("选中");
delbtn = new JButton("撤销");
pane = new JPanel();
pane.add(addbtn);
pane.add(delbtn);
addbtn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int i;
if(e.getSource()==addbtn){
for(i=0;i<orignmodel.getSize();i++)
if(orignlist.isSelectedIndex(i))
destmodel.addElement(orignmodel.elementAt(i));
for(i--;i>=0;i++)
if(orignlist.isSelectedIndex(i))
orignmodel.removeElementAt(i);
}
}
});
delbtn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int i;
if(e.getSource()==delbtn){
for(i=0;i<destmodel.getSize();i++)
if(destlist.isSelectedIndex(i))
orignmodel.addElement(destmodel.elementAt(i));
for(i--;i>=0;i--)
if(destlist.isSelectedIndex(i))
destmodel.removeElementAt(i);
}
}
});
con.add(pane,BorderLayout.SOUTH);
mainframe.setSize(300, 300);
mainframe.setVisible(true);
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new demoJList();
}
}