⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 booktablemodel.java

📁 本代码是一个关于如何对JTable进行排序的程序
💻 JAVA
字号:
import javax.swing.table.AbstractTableModel;
import java.util.Vector;
import java.util.Collection;

public class BookTableModel extends AbstractTableModel {
	private static final String headers[] = {
		"书号", "书名", "作者", "价格", "备注"
	};
	
	private Vector books = new Vector();
	
	public BookTableModel() {
		
	}
	
	public void addBooks(Collection books) {
		this.books.addAll(books);
		this.fireTableDataChanged();
	}
	
	
	public int getColumnCount() {
		return headers.length;
	}
	
	public String getColumnName(int col) {
		return headers[col];
	}
	
	public int getRowCount() {
		return books.size();
	}
	
	public Object getValueAt(int row, int col) {
		Book b = (Book)books.get(row);
		
		switch(col) {
			case 0:
				return b.getNo();
			case 1:
				return b.getName();
			case 2:
				return b.getAuthor();
			case 3:
				return b.getPrice() + "";
			case 4:
				return b.getRemark();
			default:
				return null;
		}
	}
	
	public void sortColumn(int col) {
      int out, in, min;

      for(out=0; out<books.size()-1; out++)   // outer loop
         {
         min = out;                     // minimum
         for(in=out+1; in<books.size(); in++) // inner loop
            if(compareBooks((Book)books.get(in), (Book)books.get(min), col) < 0 )         // if min greater,
                min = in;               // we have a new min
         swap(out, min);                // swap them
         }  // end for(out)
	}
	
	private void swap(int one, int two)
	{
		if(one == two)
			return;
			
		if(one > two) {
			int tmp = one;
			one = two;
			two = tmp;
		}

		Object o = books.remove(two);
		books.insertElementAt(o, one);
		
		o = books.remove(one + 1);
		books.insertElementAt(o, two-1);
	}
	
	private int compareBooks(Book b1, Book b2, int compareWho) {
		switch(compareWho) {
			case 0:
				return b1.getNo().compareTo(b2.getNo());
			case 1:
				return b1.getName().compareTo(b2.getName());
			case 2:
				return b1.getAuthor().compareTo(b2.getAuthor());
			case 3:
				if(b1.getPrice() == b2.getPrice())
					return 0;
					
				return b1.getPrice()>b2.getPrice()? 1 : -1;
			case 4:
				return b1.getRemark().compareTo(b2.getRemark());
		}
		return 0;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -