1个回答
展开全部
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
public class JTableTest extends JFrame {
private JPanel searchPanel;
private JTextField searchField;
private JButton searchButton;
private JTable table;
private TestTableModel tableModel;
public JTableTest() {
super("Simple JTable Test");
setSize(400, 300);
searchPanel = new JPanel();
searchField = new JTextField(20);
searchPanel.add(searchField);
searchButton = new JButton("搜索");
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
table.getSelectionModel().clearSelection();
doSearch();
}
});
searchPanel.add(searchButton);
getContentPane().add(searchPanel, BorderLayout.NORTH);
tableModel = new TestTableModel();
tableModel.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
if (tableModel.getHitRowCount() > 0) {
table.setRowSelectionInterval(0, tableModel.getHitRowCount() - 1);
}
}
});
table = new JTable(tableModel);
JScrollPane jsp = new JScrollPane(table);
getContentPane().add(jsp, BorderLayout.CENTER);
}
private void doSearch() {
tableModel.doSearch(searchField.getText());
}
public static void main(String[] args) {
JTableTest self = new JTableTest();
self.setVisible(true);
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class TestTableModel extends AbstractTableModel {
private List<String> data = Arrays.asList("王二", "王二小", "张三", "张三丰", "李四", "李四光");
private List<Integer> searchHitRows = new ArrayList<Integer>();
@Override
public int getRowCount() {
return data.size();
}
@Override
public int getColumnCount() {
return 1;
}
@Override
public String getColumnName(int column) {
return "姓名";
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return rowIndex < data.size() ? data.get(rowIndex) : null;
}
public void doSearch(String key) {
searchHitRows.clear();
if (key == null || "".equals(key))
return;
for (int i = 0; i < data.size(); i++) {
String value = data.get(i);
if (value.indexOf(key) < 0)
continue;
int j = 0;
for (j = i - 1; j >= 0; j--) {
String valueJ = data.get(j);
if (valueJ.indexOf(key) >= 0)
break;
}
String temp = data.get(j + 1);
data.set(j + 1, value);
data.set(i, temp);
searchHitRows.add(Integer.valueOf(j + 1));
}
fireTableDataChanged();
}
public int getHitRowCount() {
return searchHitRows.size();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询