2009年7月16日 星期四

JTable, RowSorter, SelectionModel

JTable 行排序以及排序后如何把视图(view)上的选中行对应到模型(Model)上的行

前提条件: Sun JDK 1.6 及以上版本

排序的简单实现
--------------
最简单的实现办法如下代码示意:
jtable.setRowSorter( new TableRowSorter(model) )

参数 model 代表 TableModel 的实现类.

以上代码仅示意,你可以扩展抽象类 javax.swing.RowSorter 来实现定制.



选中的行 index 和模型上的 index
--------------------------------
自 jdk 1.6 , JTable 新增了方法 public int convertRowIndexToModel(int viewRowIndex)
至此,就获得了行索引在视图与模型间的对应关系.以下列出关键代码

jtable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
int i= jtable.getSelectedRow();

if (i >= 0) {
int R = jtable.convertRowIndexToModel(i);
StudentTableModel model = (StudentTableModel)jtable.getModel();
Student s= model.getRowAt(R);
textArea.setText(String.format("index to model = %d\tindex to view = %d\tobject = %s", R, i, s==null?"?" : s.toString()));
}
}
});

后文贴出完整源代码.源代码总共3个文件: Student.java; StudentTableModel.java; SortableTable.java
SortableTable.java 是启动类

Student.java
----------------
import java.util.*;
/**
* @author Hardneedl
*/
class Student {
private String name;
private String id;
private java.util.Date birthday;

Student(String id, String name, Date d) {
this.setId(id);
this.setName(name);
this.setBirthday(d);
}
Student() {}
public String getName() {return name;}
public void setName(String name) {this.name = name;}

public String getId() {return id;}
public void setId(String id) {this.id = id;}

public java.util.Date getBirthday() {return birthday;}
public void setBirthday(java.util.Date birthday) {this.birthday = birthday;}

public boolean equals(Object obj) {
if (obj instanceof Student) {
Student st = (Student)obj;
String i = st.getId();
return i!=null && i.equals(getId());
}
return false;
}

public String toString() {return getName();}
}


StudentTableModel.java


import javax.swing.table.*;
import java.util.*;
/**
* @author Hardneedl
*/
class StudentTableModel extends AbstractTableModel {
private java.util.List studentList = new java.util.ArrayList(0);

StudentTableModel() {}
StudentTableModel(List studentList) {
this();
this.studentList.clear();
if (studentList != null) this.studentList.addAll(studentList);
}

void setDatas(java.util.Liststudents){
studentList.clear();
if (students!=null) studentList.addAll(students);
}

void addStudent(Student s){
if(s!=null) {
studentList.add(s);
fireTableDataChanged();
}
}
void removeStudent(Student s){
if (s!=null) {
studentList.remove(s);
fireTableDataChanged();
}
}

public int getRowCount() {return studentList.size();}
public int getColumnCount() {return 3;}
public Object getValueAt(int r, int c) {
Student st = studentList.get(r);
switch(c){
case 0:return st.getId();
case 1:return st.getName();
case 2:return st.getBirthday();
default:return null;
}
}

public String getColumnName(int column) {
switch(column){
case 0:return "ID";
case 1:return "Name";
case 2:return "Birthday";
default:return "???";
}
}

public void setValueAt(Object value, int rowIndex, int columnIndex) {
Student st = studentList.get(rowIndex);
if (st == null) return;
switch(columnIndex) {
case 0:
st.setId(value.toString());
break;

case 1:
st.setName(value.toString());
break;

case 2:
if (value instanceof Date)
st.setBirthday((Date)value);
break;

}
}
public boolean isCellEditable(int rowIndex, int columnIndex) {return true;}
Student getRowAt(int r){return studentList.get(r);}
}


SortableTable.java

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;
import java.text.*;
/**
* @author Hardneedl
*/
class SortableTable extends JFrame {
private static final Dimension minSize = new Dimension(300, 200);
private static final Dimension maxSize = new Dimension(1024, 768);
private static final Dimension preferredSize = new Dimension(600, 400);

private JTable jtable;
private JTextArea textArea;
public Dimension getMaximumSize() {return maxSize;}
public Dimension getMinimumSize() {return minSize;}
public Dimension getPreferredSize() {return preferredSize;}
public String getTitle() {return "JTable Sort Demo";}

SortableTable() throws HeadlessException {init();doLay();attachListeners();}

private void init() {
StudentTableModel model=new StudentTableModel();
model.addStudent(new Student("1", "Martin", new Date(Calendar.getInstance().getTimeInMillis())));
model.addStudent(new Student("2", "Rose", new Date(Calendar.getInstance().getTimeInMillis())));
model.addStudent(new Student("3", "Daisy", new Date(Calendar.getInstance().getTimeInMillis())));
model.addStudent(new Student("4", "Tom", new Date(Calendar.getInstance().getTimeInMillis())));
model.addStudent(new Student("5", "Needl", new Date(Calendar.getInstance().getTimeInMillis())));

jtable = new JTable(model);
jtable.setRowSorter( new TableRowSorter(model) );
jtable.getColumnModel().getColumn(2).setCellRenderer(new DefaultTableCellRenderer(){
private SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component cmp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setText(dateFormat.format(value));
setHorizontalAlignment(SwingConstants.RIGHT);
return cmp;
}
});


jtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

textArea = new JTextArea(){
public Color getBackground() {return Color.ORANGE;}
public Color getForeground() {return Color.BLUE;}
public boolean isEditable() {return false;}
};
}

private void doLay() {
Container container = getContentPane();
container.add(new JScrollPane(jtable), BorderLayout.CENTER);
container.add(textArea, BorderLayout.SOUTH);
pack();
}

private void attachListeners() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
int i= jtable.getSelectedRow();

if (i >= 0) {
int R = jtable.convertRowIndexToModel(i);
StudentTableModel model = (StudentTableModel)jtable.getModel();
Student s= model.getRowAt(R);
textArea.setText(String.format("index to model = %d\tindex to view = %d\tobject = %s", R, i, s==null?"?" : s.toString()));
}
}
});
}

public static void main(String[] args) {new SortableTable().setVisible(true);}
}



source: http://hi.baidu.com/hardneedl/blog/

沒有留言: