`
hizhangqi
  • 浏览: 89467 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

共享一个Swing JTable组件的CheckBox管理类

 
阅读更多
surce :http://danferj.iteye.com/blog/525889

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class TableCheckboxManager {

public static final int SELECT_PART = 0;

public static final int SELECT_ALL = 1;

public static final int SELECT_NONE = 2;

// private List<JCheckBox> tableCheck = new ArrayList<JCheckBox>(); //
// @jve:decl-index=0:

private byte[] tableCheck = new byte[0]; // @jve:decl-index=0:

private IndexJCheckBox[] templetBox = new IndexJCheckBox[] {
new IndexJCheckBox((String) null, false),
new IndexJCheckBox((String) null, true) };

private JTable table;

private JCheckBox headerCheckBox;

private int checkStata = -1;

private Map<Integer, Object> selectedIndexMap = new HashMap<Integer, Object>();

private int tableCheckedCount = 0;

private boolean fireChanged = true;

// private IndexJCheckBox addCheckBox = null;

private int headerCheckBoxColumn = 0;

private int checkBoxColumn = 0;

private static final int DFAULT_MAX_WIDTH = 23;

private static final int DFAULT_MIN_WIDTH = 23;

private static final int DFAULT_PREFERRED_WIDTH = 23;

private int maxWidth = DFAULT_MAX_WIDTH;

private int minWidth = DFAULT_MIN_WIDTH;

private int preferredWidth = DFAULT_PREFERRED_WIDTH;

private IndexJCheckBox editorCheckBox = new IndexJCheckBox();

private MouseListener nowMouseListen = null;

// private ChangeListener checkChange = new ChangeListener() {
// public void stateChanged(ChangeEvent e) {
// checkedChanged((JCheckBox) e.getSource());
// }
// };

private ActionListener actionChange = new ActionListener() {
public void actionPerformed(ActionEvent e) {
clickCheckBox(table.getEditingRow());
checkedChanged2(table.getEditingRow());
}
};

public TableCheckboxManager(JTable table, List<JCheckBox> checkBoxs) {
this.table = table;
addTableMouseListener();
setColumnAttributes();
saveCheckBoxListStata(checkBoxs);
}

public void close() {
clear();
table = null;
}

private void clear() {
tableCheck = new byte[0];

table = null;

headerCheckBox = null;

checkStata = -1;

selectedIndexMap = new HashMap<Integer, Object>();

tableCheckedCount = 0;

fireChanged = true;

// addCheckBox = null;

headerCheckBoxColumn = 0;

checkBoxColumn = 0;

removeSet();
}

public void setCheckBoxColumn(int col) {
checkBoxColumn = col;
if (table != null) {
setColumnAttributes();
}
}

public void setSelected(int[] indexs) {
for (int i = 0; i < indexs.length; i++) {
tableCheck[indexs[i]] = 1;
tableCheckedCount++;
}
updateStata();
table.revalidate();
table.repaint();
}

private void setColumnAttributes() {
TableColumn tc = table.getColumnModel().getColumn(checkBoxColumn);
tc.setPreferredWidth(preferredWidth);
tc.setMaxWidth(maxWidth);
tc.setMinWidth(minWidth);
tc.setCellRenderer(getCheckBoxsCellRenderer());
tc.setCellEditor(getCheckBoxsCellEditor(true));
}

private void addTableMouseListener() {
nowMouseListen = new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
if (e.getButton() != java.awt.event.MouseEvent.BUTTON1)
return;
if (e.getClickCount() == 1) {
int selectRow = TableCheckboxManager.this.table
.getSelectedRow();
if (selectRow > -1) {
int col = TableCheckboxManager.this.table
.columnAtPoint(e.getPoint());
if (col != -1 && col == checkBoxColumn) {
clickCheckBox(selectRow);
checkedChanged(selectRow);
table.revalidate();
table.repaint();
}
}
}
}

/**
* Invoked when the mouse exits a component.
*/
public void mouseExited(MouseEvent e) {
}
};
table.addMouseListener(nowMouseListen);
}

public TableCheckboxManager(List<JCheckBox> checkBoxs) {
saveCheckBoxListStata(checkBoxs);
}

public TableCheckboxManager() {
}

private void saveCheckBoxListStata(List<JCheckBox> checkBoxs) {
tableCheck = new byte[checkBoxs.size()];
for (int i = 0; i < checkBoxs.size(); i++) {
tableCheck[i] = (byte) (checkBoxs.get(i).isSelected() ? 1 : 0);
}
}

public void setTable(JTable table) {
clear();
boolean addMouseLisen = false;
if (this.table != table) {
addMouseLisen = true;
}
if (addMouseLisen) {
this.table = table;
addTableMouseListener();
setColumnAttributes();
}
}

public void removeSet() {
if (table != null) {
table.removeMouseListener(nowMouseListen);
TableColumn tc = table.getColumnModel().getColumn(checkBoxColumn);
tc.setCellRenderer(null);
tc.setCellEditor(null);
}
}

public TableCheckboxManager(JTable table) {
this.table = table;
addTableMouseListener();
setColumnAttributes();
}

public JCheckBox getCheckBox(int i) {
return templetBox[tableCheck[i]];
}

public boolean isSelected(int i) {
return tableCheck[i] == 0 ? false : true;
}

public int size() {
return tableCheck.length;
}

public void clearCheckBoxList() {
createCheckBoxList();
}

public void createCheckBoxList() {
tableCheck = new byte[0];
selectedIndexMap = new HashMap<Integer, Object>();
tableCheckedCount = 0;
checkStata = -1;
selectLogicCheckBoxChecked(true);
}

public void resetCheckBox(int size) {
createCheckBoxList();
addCheckBoxs(size);
checkStata--;
selectLogicCheckBoxChecked(true);
}

// public List<JCheckBox> getCheckBoxList() {
// return tableCheck;
// }

// public void setCheckBoxList(List<JCheckBox> checkBoxList) {
// tableCheck = checkBoxList;
// }

public JTable getTable() {
return this.table;
}

{
initCheckBox();
}

public void initCheckBox() {
for (int i = 0; i < templetBox.length; i++) {
// templetBox[i].addChangeListener(checkChange);
templetBox[i].setVisible(true);
}
editorCheckBox.addActionListener(actionChange);
editorCheckBox.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (table.getEditingRow() > 0
&& table.getEditingRow() < tableCheck.length) {
editorCheckBox
.setSelected(tableCheck[table.getEditingRow()] == 0 ? false
: true);
}
}
});
}

public void addCheckBoxs(int size) {
tableCheck = new byte[size];
// addTableMouseListener();
// setColumnAttributes();
}

public void setHeaderShowCheckbox(int col) {
headerCheckBoxColumn = col;
final JTableHeader jh = table.getTableHeader();
TableColumnModel headerColumnMode = jh.getColumnModel();

headerColumnMode.getColumn(0).setHeaderRenderer(
new TableHeaderRenderer(getHeaderCheckBox()));
jh.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
int column;
if ((column = jh.columnAtPoint(e.getPoint())) != -1) {
TableColumn tc = table.getColumnModel().getColumn(
checkBoxColumn);
tc.getCellEditor().cancelCellEditing();
if (column == headerCheckBoxColumn) {
selectLogicCheckBoxChecked(true);
jh.repaint();
}
}
}
});
}

private void selectLogicCheckBoxChecked(boolean seleteSaveTable) {
checkStata++;
if (checkStata == 3) {
checkStata = 0;
}
switch (checkStata) {
case SELECT_PART:
getHeaderCheckBox().setSelected(true);
getHeaderCheckBox().setEnabled(false);
if (seleteSaveTable) {
seletedCheckBoxCheck();
}
break;
case SELECT_ALL:
getHeaderCheckBox().setSelected(true);
getHeaderCheckBox().setEnabled(true);
if (seleteSaveTable) {
selectAllTable(true);
}
break;
case SELECT_NONE:
getHeaderCheckBox().setSelected(false);
getHeaderCheckBox().setEnabled(true);
if (seleteSaveTable) {
selectAllTable(false);
}
break;
}
table.getTableHeader().repaint();
}

private void checkedChanged(int index) {
if (fireChanged && !table.isEditing()) {
changeStata(index);
}
}

private void checkedChanged2(int index) {
if (table.isEditing()) {
changeStata(index);
}
}

private void changeStata(int index) {

if (checkStata == SELECT_NONE) {
selectedIndexMap = new HashMap<Integer, Object>();
}

if (checkStata == SELECT_ALL) {
selectedIndexMap = new HashMap<Integer, Object>();
for (int i = 0; i < tableCheck.length; i++) {
selectedIndexMap.put(i, null);
}
}

if (tableCheck[index] == 1) {
tableCheckedCount++;
selectedIndexMap.put(index, null);
} else {
tableCheckedCount--;
selectedIndexMap.remove(index);
}

updateStata();
}

private void updateStata() {
int changedStata = 0;
if (tableCheckedCount != 0) {
if (tableCheckedCount == tableCheck.length) {
changedStata = SELECT_ALL;
} else {
changedStata = SELECT_PART;
}
} else {
changedStata = SELECT_NONE;
}

if (changedStata != checkStata) {
changedStata--;
checkStata = changedStata;
selectLogicCheckBoxChecked(false);
table.getTableHeader().repaint();
}
}

private void selectAllTable(boolean check) {
fireChanged = false;
byte nowCheckStata = (byte) (check ? 1 : 0);
for (int i = 0; i < tableCheck.length; i++) {
tableCheck[i] = nowCheckStata;
}
if (check) {
tableCheckedCount = tableCheck.length;
} else {
tableCheckedCount = 0;
}
table.revalidate();
table.repaint();
fireChanged = true;
}

private JCheckBox getHeaderCheckBox() {
if (headerCheckBox == null) {
headerCheckBox = new JCheckBox();
headerCheckBox.setBorderPainted(true);
}
return headerCheckBox;
}

private void clickCheckBox(int i) {
if (tableCheck != null) {
tableCheck[i] = (byte) (tableCheck[i] == 0 ? 1 : 0);
}
}

protected class TableHeaderRenderer implements TableCellRenderer {
private JCheckBox renderCheckBoxs;

public TableHeaderRenderer(JCheckBox tableCheck) {
renderCheckBoxs = tableCheck;
}

public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
return renderCheckBoxs;
}
}

private void seletedCheckBoxCheck() {
fireChanged = false;
tableCheckedCount = 0;

Set<Integer> keys = selectedIndexMap.keySet();
int checkIndex = 0;
for (Iterator<Integer> keyItr = keys.iterator(); keyItr.hasNext();) {
checkIndex = keyItr.next();
if (tableCheck.length > checkIndex) {
tableCheck[checkIndex] = 1;
tableCheckedCount++;
}
}

if (tableCheckedCount == 0) {
selectLogicCheckBoxChecked(true);
} else if (tableCheck.length > 0
&& tableCheckedCount == tableCheck.length) {
selectLogicCheckBoxChecked(false);
}
table.revalidate();
table.repaint();
fireChanged = true;
}

public void changeCheckBoxStata(int... stata) {
for (int i = 0; i < stata.length; i++) {
checkStata = stata[i] - 1;
selectLogicCheckBoxChecked(true);
if (checkStata == stata[i]) {
break;
}
}
}

public void clearAndChangeCheckBoxStata(int... stata) {
clearSelect();
changeCheckBoxStata(stata);
}

private void clearSelect() {
selectAllTable(false);
}

public void setSelectedCheckIndexs(List<Integer> selectedInx) {
selectedIndexMap = new HashMap<Integer, Object>();
for (int i = 0; i < selectedInx.size(); i++) {
selectedIndexMap.put(selectedInx.get(i), null);
}
}

public TableCellEditor getCheckBoxsCellEditor(boolean addListener) {
TableCellEditor tce = new CheckBoxsCellEditor();
if (addListener)
tce.addCellEditorListener(new CheckBoxCellEditorListener());
return tce;
}

public TableCellRenderer getCheckBoxsCellRenderer() {
return new CheckBoxsRenderer();
}

class CheckBoxsCellEditor extends DefaultCellEditor {

private static final long serialVersionUID = -1875319868682535006L;

public CheckBoxsCellEditor() {
super(new JTextField());
}

public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
return editorCheckBox;
}
}

protected class CheckBoxsRenderer implements TableCellRenderer {

public CheckBoxsRenderer() {
}

public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
if (row < tableCheck.length) {
return (Component) templetBox[tableCheck[row]];
}
return null;
}
}

private class IndexJCheckBox extends JCheckBox {
public IndexJCheckBox(String text, boolean selected) {
super(text, selected);
}

public IndexJCheckBox() {
super();
}

private static final long serialVersionUID = 1L;

private int index = 0;

public int getIndex() {
return index;
}

public void setIndex(int index) {
this.index = index;
}
}

public Set<Integer> getSelectedIndexSet() {
switch (checkStata) {
case SELECT_PART:
return selectedIndexMap.keySet();
case SELECT_ALL:
HashSet<Integer> allItem = new HashSet<Integer>();
for (int i = 0; i < tableCheck.length; i++) {
allItem.add(i);
}
return allItem;
case SELECT_NONE:
return new HashSet<Integer>();
}
return new HashSet<Integer>();
}

class CheckBoxCellEditorListener implements CellEditorListener {
int row;

int col;

public void editingStopped(ChangeEvent e) {
table.revalidate();
table.repaint();
// editorCheckBox
// .setSelected(tableCheck[table.getEditingRow()] == 0 ? false
// : true);
// editorCheckBox.setIndex(table.getEditingRow());
}

public void editingCanceled(ChangeEvent e) {
table.revalidate();
table.repaint();
}

}

public void removeAllSelectedIndex() {
selectedIndexMap = new HashMap<Integer, Object>();
tableCheckedCount = 0;
updateStata();
}

public Integer[] getSortedSelectedIndexs() {
Set<Integer> selectIndex = getSelectedIndexSet();
Integer[] indexs = new Integer[selectIndex.size()];
indexs = selectIndex.toArray(indexs);
Arrays.sort(indexs);
return indexs;
}

public void removeAllSelectedIndexAndCheckBox() {
Integer[] indexs = getSortedSelectedIndexs();
tableCheck = new byte[tableCheck.length - indexs.length];
}

public void removeAllSelectedIndexAndCheckBox(Integer[] indexs) {
tableCheck = new byte[tableCheck.length - indexs.length];
for (int i = indexs.length - 1; i >= 0; i--) {
selectedIndexMap.remove(indexs[i]);
}
tableCheckedCount = selectedIndexMap.size();
updateStata();
}

/**
* maxWidth傪曉偟傑偡丅
*
* @return maxWidth
*/
public int getMaxWidth() {
return maxWidth;
}

/**
* maxWidth傪愝掕偟傑偡丅
*
* @param maxWidth
*            maxWidth傊愝掕
*/
public void setMaxWidth(int maxWidth) {
this.maxWidth = maxWidth;
}

/**
* minWidth傪曉偟傑偡丅
*
* @return minWidth
*/
public int getMinWidth() {
return minWidth;
}

/**
* minWidth傪愝掕偟傑偡丅
*
* @param minWidth
*            minWidth傊愝掕
*/
public void setMinWidth(int minWidth) {
this.minWidth = minWidth;
}

/**
* preferredWidth傪曉偟傑偡丅
*
* @return preferredWidth
*/
public int getPreferredWidth() {
return preferredWidth;
}

/**
* preferredWidth傪愝掕偟傑偡丅
*
* @param preferredWidth
*            preferredWidth傊愝掕
*/
public void setPreferredWidth(int preferredWidth) {
this.preferredWidth = preferredWidth;
}
}

调用代码:
// 创建一个对象,并将要管理的table传入
TableCheckboxManager tablesCheckBoxMgr = new TableCheckboxManager(jTable);
// 设置table中checkbox的数量
tablesCheckBoxMgr.addCheckBoxs(20);
// 设置表头checkbox的列
tablesCheckBoxMgr.setHeaderShowCheckbox(0);
// 设置选中的行
tablesCheckBoxMgr.setSelected(new int[]{0,1,2,4});

分享到:
评论

相关推荐

    swing Jtable使用checkbox

    swing Jtable使用checkboxswing Jtable使用checkboxswing Jtable使用checkboxswing Jtable使用checkboxswing Jtable使用checkboxswing Jtable使用checkboxswing Jtable使用checkboxswing Jtable使用checkboxswing ...

    Swing JTable组件设置单元格合并

    Swing JTable组件设置单元格合并,内置Test测试类,核心API GridBagTable tasktable = new GridBagTable(model); tasktable.mergeCells(startRow, endRow, 0, 0);

    JTable添加CheckBox

    在Java Swing中,`JTable` 是用于展示二维数据的组件,它允许用户查看和编辑数据。本示例探讨如何在`JTable`中添加`CheckBox`,并实现表头的`JCheckBox`全选联动功能。这在需要用户进行多选操作的界面中非常常见,...

    Java Swing JTable分页

    对于表格形式的数据展示,`JTable`是一个非常常用且强大的组件。然而,当数据量过大时,一次性加载所有数据不仅会消耗大量的内存资源,还会影响用户的操作体验。因此,实现`JTable`的分页功能就显得尤为重要。 ####...

    Java Swing高级空件JTable的用法

    例如,将一个JavaBean对象的属性展示在JTable中,只需要将JavaBean对象转换为TableModel接口的实现,然后将其传递给JTable组件。 4. JTable的美化 JTable组件可以通过设置表格的宽度和高度、显示表头、添加列、...

    Java Swing Menu组件,JTable组件,JTree组件小示例

    通常,它会包含一个主类,创建并设置这些组件,然后将它们添加到容器(如`JFrame`)中,最后设置窗口的基本属性如大小和位置,并调用`setVisible(true)`使其可见。 总结起来,`Java Swing`中的`JMenu`、`JTable`和`...

    java Swing Jtable 下拉动态加载数据

    JTable实现下拉动态加载数据,滑动动态加载数据,纯原生态java。

    Swing之JTable的详细介绍

    Swing中的JTable组件是Java GUI开发中用于展示表格数据的重要工具,它是Swing库中的一个核心组件。JTable能够方便地创建和管理表格数据,同时也支持用户交互,如编辑单元格、排序、选择行等操作。下面我们将深入探讨...

    java swing 导出Jtable里面的数据到excel

    java swing 导出Jtable里面的数据到excel,不用拷贝代码,直接粘贴代码

    Swing 扩展组件 Swing 扩展组件

    Swing扩展组件是Java Swing库中的一个重要组成部分,它提供了丰富的用户界面元素,使得开发者能够创建出功能强大且具有吸引力的图形用户界面(GUI)。Swing是Java AWT(抽象窗口工具包)的一个替代品,提供了更多的...

    Jtable 中放入多个按钮

    在Java Swing库中,`JTable`是一个非常重要的组件,用于展示二维数据表格。当我们需要在`JTable`中实现更复杂的交互,比如在一个单元格内放置多个按钮时,这通常涉及到自定义`TableCellRenderer`和`TableCellEditor`...

    Swing JTable 常用属性

    可以直接使用 JTable 的无参构造函数创建一个空的表格控件,例如:`JTable table = new JTable();` 2. 以表头和表数据创建表格 可以使用表头和表数据创建一个 JTable,例如: ``` Object[][] cellData = {{"row1-...

    swing表格分页控件封装

    java swing表格分页控件封装,有利于在开发中节约时间

    Java Swing实现JTable检测单元格数据变更事件的方法示例

    Java Swing 中的 JTable 是一个功能强大且灵活的表格组件,广泛应用于各种桌面应用程序中。然而,在实际开发中,我们经常需要检测单元格数据的变更事件,以便实时响应用户的操作。今天,我们将探讨 Java Swing 中...

    Swing中JTABLE中添加JBUTTON控件

    在Java的Swing库中,`JTable`是用于创建数据网格视图的重要组件,它允许用户以表格的形式查看和操作数据。而`JButton`则是一个常用的按钮控件,通常用于触发某些动作或事件。将`JButton`添加到`JTable`中可以为用户...

    swing jtable 合并

    在Swing中,`JTable`是一个非常重要的组件,它用于显示和编辑表格数据。`JTable`可以用于显示二维数据,比如数据库记录或者任何其他表格格式的数据。在本篇中,我们将深入探讨`JTable`的使用,包括它的合并功能。 ...

    JAVA中JTable组件详解实例

    在Java Swing中,`JTable` 是一个非常重要的组件,用于展示二维表格数据。它不仅功能强大而且使用灵活,适用于各种应用程序中需要显示和编辑表格数据的场景。本文将详细介绍`JTable`的基本用法及其常见操作,包括...

    Swing之JTable详解

    1. `JTable()`: 构建一个新的`JTable`,并使用系统默认的模型(通常是`DefaultTableModel`)。 2. `JTable(int numRows, int numColumns)`: 创建一个指定行数和列数的空表格,同样使用`DefaultTableModel`作为数据...

    复杂JTable-跨列表头

    在Java Swing库中,JTable是一个非常重要的组件,用于显示和操作二维数据集。这个组件在用户界面设计中广泛使用,因为它提供了丰富的交互性,包括排序、选择和编辑表格数据。"复杂JTable-跨列表头"是一个特殊实现,...

Global site tag (gtag.js) - Google Analytics