JList雙向列表

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class JListDemo7 extends MouseAdapter{
	JList list = null;
	JList list2 = null;
	DefaultListModel mode = null;
	DefaultListModel mode2= null;
	String[] s ={"美國","日本","中國","英國","法國","德國"};
	
	public JListDemo7(){
		JFrame jf = new JFrame();
		Container contentPane = jf.getContentPane();
		contentPane.setLayout(new GridLayout(1,2));
		
		mode = new DataModel4(1);
		list = new JList(mode);
		list.setBorder(BorderFactory.createTitledBorder("國家名稱"));
		list.addMouseListener(this);
		
		mode2 = new DataModel4(2);
		list2 = new JList(mode2);
		list2.setBorder(BorderFactory.createTitledBorder("你喜歡哪個國家呢?"));
		list2.addMouseListener(this);
		
		contentPane.add(new JScrollPane(list));
		contentPane.add(new JScrollPane(list2));
		jf.pack();
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}
	
	@Override
	public void mouseClicked(MouseEvent e){
		int index;
		if(e.getSource()==list){
			if(e.getClickCount()==2){
				index = list.locationToIndex(e.getPoint());
				String stmp = (String)mode.getElementAt(index);
				mode2.addElement(stmp);
				list2.setModel(mode2);
				mode.removeElementAt(index);
				list.setModel(mode);
			}
		}
		if(e.getSource()==list2){
			if(e.getClickCount()==2){
				index = list2.locationToIndex(e.getPoint());
				String stmp = (String)mode2.getElementAt(index);
				mode.addElement(stmp);
				mode2.removeElementAt(index);
				list.setModel(mode);
				list2.setModel(mode2);
			}
		}
	}
	
	public static void main(String...args){
		new JListDemo7();
	}
	
	class DataModel4 extends DefaultListModel{
		DataModel4(int flag){
			if(flag==1){
				for(int i=0;i<s.length;i++){
					addElement(s[i]);
				}
			}
		}
	}
}


摘自:深入淺出Java Swing程序設計

你可能感兴趣的:(java,swing)