1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| public class Demo {
public static void main(String[] args) {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object[][] data = {
{ false, "aaaa" },
{ false, "bbbb" },
{ false, "cccc" },
{ false, "dddd" }
};
String[] columns = { "Sélection", "Libellé" };
TableModel model = new DefaultTableModel(data, columns) {
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnIndex==0?Boolean.class:String.class;
}
};
JTable table = new JTable(model);
frame.add(new JScrollPane(table));
JLabel label = new JLabel();
frame.add(label, BorderLayout.SOUTH);
model.addTableModelListener(e-> {
if ( e.getType()==TableModelEvent.UPDATE ) {
setLabelText(model, label);
}
});
setLabelText(model, label);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static final MessageFormat LABEL_FORMAT = new MessageFormat("Vous avez sélectionné {0,choice,0#aucune case|1#une case|1<{0} cases}");
private static void setLabelText(TableModel model, JLabel label) {
int nb=0;
for(int i=0; i<model.getRowCount(); i++) {
if ( (Boolean)model.getValueAt(i, 0) ) {
nb++;
}
}
Object[] params = {nb};
label.setText(LABEL_FORMAT.format(params));
}
} |
Partager