java复选框互斥_使用setValueAt重新创建互斥复选框

不要添加自己的MouseListener。而是setValueAt()在中TableModel进行覆盖以查看默认编辑器为设置的新值Boolean.class。

附录:这是一个sscce。为了方便起见,只需清除中的所有条目CHECK_COL,设置新值并相应地调节按钮。

import java.awt.*;

import javax.swing.*;

import javax.swing.table.DefaultTableModel;

/**

* @see http://stackoverflow.com/questions/7920068

* @see http://stackoverflow.com/questions/4526779

*/

public class CheckOne extends JPanel {

private static final int CHECK_COL = 1;

private static final Object[][] DATA = {

{"One", Boolean.FALSE}, {"Two", Boolean.FALSE},

{"Three", Boolean.FALSE}, {"Four", Boolean.FALSE},

{"Five", Boolean.FALSE}, {"Six", Boolean.FALSE},

{"Seven", Boolean.FALSE}, {"Eight", Boolean.FALSE},

{"Nine", Boolean.FALSE}, {"Ten", Boolean.FALSE}};

private static final String[] COLUMNS = {"Number", "CheckBox"};

private DataModel dataModel = new DataModel(DATA, COLUMNS);

private JTable table = new JTable(dataModel);

private ControlPanel cp = new ControlPanel();

public CheckOne() {

super(new BorderLayout());

this.add(new JScrollPane(table));

this.add(cp, BorderLayout.SOUTH);

table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

table.setPreferredScrollableViewportSize(new Dimension(250, 175));

}

private class DataModel extends DefaultTableModel {

public DataModel(Object[][] data, Object[] columnNames) {

super(data, columnNames);

}

@Override

public void setValueAt(Object aValue, int row, int col) {

if (col == CHECK_COL) {

for (int r = 0; r < getRowCount(); r++) {

super.setValueAt(false, r, CHECK_COL);

}

}

super.setValueAt(aValue, row, col);

cp.button.setEnabled(any());

}

private boolean any() {

boolean result = false;

for (int r = 0; r < getRowCount(); r++) {

Boolean b = (Boolean) getValueAt(r, CHECK_COL);

result |= b;

}

return result;

}

@Override

public Class> getColumnClass(int col) {

if (col == CHECK_COL) {

return getValueAt(0, CHECK_COL).getClass();

}

return super.getColumnClass(col);

}

@Override

public boolean isCellEditable(int row, int col) {

return col == CHECK_COL;

}

}

private class ControlPanel extends JPanel {

JButton button = new JButton("Button");

public ControlPanel() {

button.setEnabled(false);

this.add(new JLabel("Selection:"));

this.add(button);

}

}

private static void createAndShowUI() {

JFrame frame = new JFrame("CheckOne");

frame.add(new CheckOne());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

public static void main(String[] args) {

java.awt.EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

createAndShowUI();

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值