JList不同的列表模式

JLsit(ListModel mode):其中ListModel可以是:
    ListModel接口:要重寫addListDataListener() removeListDataListener() getSize()  getElementAt()方法
    AbstractListModel抽象類:要重寫getSize()  getElementAt()方法
    DefaultListModel類:不需要重寫任何方法,而且DefaultListModel具有Vector功能,可以addElement()  removeElement()  getElementAt()  copyInto()等操作。

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

public class JListDemo4 {

	public JListDemo4(){
		JFrame jf = new JFrame();
		Container contentPane = jf.getContentPane();
		contentPane.setLayout(new GridLayout(1,2));
		ListModel mode = new DataModel3(1);
		JList list = new JList(mode);
		list.setBorder(BorderFactory.createTitledBorder("你用過哪些軟件?"));
		
		mode = new DataModel3(2);
		JList list2 = new JList(mode);
		list2.setBorder(BorderFactory.createTitledBorder("你用過哪些數據庫軟件?"));
		
		contentPane.add(list);
		contentPane.add(list2);
		jf.pack();
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void main(String...args){
		new JListDemo4();
	}
}

class DataModel3 extends DefaultListModel{
	String[] s = {"MS SQL","MySQL","IBM DB2","ORACLE","Windows 2000","Linux","Unix","OS2"};
	int flag;
	
	DataModel3(int flag){
		this.flag = flag;
	}
	@Override
	public Object getElementAt(int index){
		String temp = null;
		if(flag==1){
			temp = (index+1)+"."+s[index];
		}
		if(flag==2){
			if(index<4){
				temp = (index+1)+"."+s[index];
			}
		}
		return temp;
		
	}
	@Override
	public int getSize(){
		return s.length;
	}
}


參考:深入淺出Java Swing程序設計

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