java jtable 复选框_java – JTable中带复选框的多行选择

我有一个带复选框的JTable作为列之一.我还在标题中有一个复选框来检查/取消选中所有.

AFAIK JTable的默认行为是,如果选择新行,它将取消选择之前选择的所有行.但是我们可以通过复选框实现CTRL点击行为.保留以前选定的行.

我面临的主要问题是使用复选框启用多个JTable行选择.

预期产出

检查第一行然后选择第一行,如果选中第三行,则选择第三行以及第一行(已经选中并选中)

实际输出

检查并选择第一行时,如果选择第三行,则取消选择先前选择的所有行,仅选择第三行.

我有一个示例代码,它模拟我想要实现的场景,与Add Another One按钮相同,但有复选框选择.

import javax.swing.*;

import javax.swing.event.ListSelectionEvent;

import javax.swing.table.AbstractTableModel;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.event.ListSelectionListener;

import javax.swing.table.TableColumn;

import javax.swing.event.CellEditorListener;

public class JTableRowSelectProgramatically extends JPanel {

final JTable table = new JTable(new MyTableModel());

public JTableRowSelectProgramatically() {

initializePanel();

}

private void initializePanel() {

setLayout(new BorderLayout());

setPreferredSize(new Dimension(475, 150));

table.setFillsViewportHeight(true);

JScrollPane pane = new JScrollPane(table);

JLabel label2 = new JLabel("Row: ");

final JTextField field2 = new JTextField(3);

JButton add = new JButton("Select");

table.setRowSelectionAllowed(true);

table.setColumnSelectionAllowed(false);

table.getSelectionModel().addListSelectionListener(new ListSelectionListenerImpl());

TableColumn tc = table.getColumnModel().getColumn(3);

tc.setCellEditor(table.getDefaultEditor(Boolean.class));

tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));

((JComponent) table.getDefaultRenderer(Boolean.class)).setOpaque(true);

tc.getCellEditor().addCellEditorListener(new CellEditorListenerImpl());

add.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

int index2 = 0;

try {

index2 = Integer.valueOf(field2.getText());

} catch (NumberFormatException e) {

e.printStackTrace();

}

table.addRowSelectionInterval(index2, index2);

field2.setText(String.valueOf(index2));

}

});

JPanel command = new JPanel(new FlowLayout());

command.add(label2);

command.add(field2);

command.add(add);

add(pane, BorderLayout.CENTER);

add(command, BorderLayout.SOUTH);

}

public static void showFrame() {

JPanel panel = new JTableRowSelectProgramatically();

panel.setOpaque(true);

JFrame frame = new JFrame("JTable Row Selection");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setContentPane(panel);

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

JTableRowSelectProgramatically.showFrame();

}

});

}

public class MyTableModel extends AbstractTableModel {

private String[] columns = {"ID", "NAME", "AGE", "A STUDENT?"};

private Object[][] data = {

{1, "Alice", 20, new Boolean(false)},

{2, "Bob", 10, new Boolean(false)},

{3, "Carol", 15, new Boolean(false)},

{4, "Mallory", 25, new Boolean(false)}

};

public int getRowCount() {

return data.length;

}

public int getColumnCount() {

return columns.length;

}

public Object getValueAt(int rowIndex, int columnIndex) {

return data[rowIndex][columnIndex];

}

@Override

public String getColumnName(int column) {

return columns[column];

}

@Override

public boolean isCellEditable(int rowIndex, int columnIndex) {

return columnIndex == 3;

}

//

// This method is used by the JTable to define the default

// renderer or editor for each cell. For example if you have

// a boolean data it will be rendered as a check box. A

// number value is right aligned.

//

@Override

public Class> getColumnClass(int columnIndex) {

return data[0][columnIndex].getClass();

}

@Override

public void setValueAt(Object aValue, int rowIndex, int columnIndex) {

if (columnIndex == 3) {

data[rowIndex][columnIndex] = aValue;

fireTableCellUpdated(rowIndex, columnIndex);

}

}

}

class ListSelectionListenerImpl implements ListSelectionListener {

public void valueChanged(ListSelectionEvent lse) {

ListSelectionModel lsm = (ListSelectionModel) lse.getSource();

int row = table.getRowCount();

if (lsm.isSelectionEmpty()) {

} else {

// If any column is clicked other than checkbox then do normal selection

// i.e select the click row and deselects the previous selection

if (table.getSelectedColumn() != 3) {

for (int i = 0; i < row; i++) {

if (lsm.isSelectedIndex(i)) {

table.setValueAt(true, i, 3);

} else {

table.setValueAt(false, i, 3);

}

}

}

}

}

}

public class CellEditorListenerImpl implements CellEditorListener{

public void editingStopped(ChangeEvent e) {

for(int i=0; i

if((Boolean)table.getValueAt(i, 3)){

table.addRowSelectionInterval(i, i);

}

else{

table.removeRowSelectionInterval(i, i);

}

}

}

public void editingCanceled(ChangeEvent e) {

System.out.println("do nothing");

}

}

}

Java Swing中,JTable是一个用于显示二维表格数据的组件。如果你想要实现JTable复选框全选功能,你可以通过以下步骤操作: 1. 首先,你需要创建一个`DefaultTableModel`,它是JTable的数据模型。在`getColumnClass()`方法中返回`Boolean.class`,以便为每一列添加一个复选框。 ```java DefaultTableModel model = new DefaultTableModel( // 表头信息 new Object[]{"ID", "Name", "Select"}, 0); model.getColumnClass(2) = Boolean.class; ``` 2. 创建JTable并设置其模型: ```java JTable table = new JTable(model); table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(new JCheckBox())); ``` 这里的`getColumn(2)`代表选择列,0通常是第一个可用列开始计数。 3. 当需要全选或反选所有时,可以监听`TableModelListener`的事件,比如`table.getModel().addTableModelListener(this)`,然后在`tableChanged`方法中处理: ```java @Override public void tableChanged(TableModelEvent e) { if (e.getType() == TableModelEvent.TABLE_CHANGED && e.getColumn() != null && e.getColumn().equals(table.getColumnModel().getColumn(2))) { int rowCount = table.getRowCount(); for (int i = 0; i < rowCount; i++) { boolean checked = e.getValueIsAdjusting() ? !table.getValueAt(i, 2).booleanValue() : true; table.setValueAt(checked, i, 2); } } } ``` 在这个例子中,`getValueIsAdjusting()`检查是否正在编辑状态,如果是则切换复选框状态,如果不是,则默认全选或全反选。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值