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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| public class Exo {
private String title[] = {"code", "nom", "qte"};
Hashtable base = new Hashtable();
Hashtable liste = new Hashtable();
JTable table;
DefaultTableModel mod;
JTextField tf;
public Exo() {
base.put("10", "10&sourie&1");
base.put("20", "20&clavier&1");
base.put("30", "30&ecron&1");
JFrame f = new JFrame();
f.setBounds(0, 0, 400, 400);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mod = new DefaultTableModel(null, title);
table = new JTable(mod) {
@Override // Always selectAll()
public boolean editCellAt(int row, int column, EventObject e) {
boolean result = super.editCellAt(row, column, e);
final Component editor = getEditorComponent();
if (editor == null || !(editor instanceof JTextComponent)) {
return result;
}
((JTextComponent) editor).selectAll();
return result;
}
};
JScrollPane sc = new JScrollPane(table);
sc.setBounds(10, 10, 350, 350);
tf = new JTextField();
TableColumn soprtColumn = table.getColumnModel().getColumn(0);
soprtColumn.setCellEditor(new DefaultCellEditor(tf));
tf.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
}
public void removeUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
if ( table.isEditing() ) {
save();
}
}
});
table.setCellSelectionEnabled(false);
mod.addRow(new Vector());
f.add(sc);
f.setVisible(true);
}
public void save() {
String prod = (String) base.get(tf.getText());
int qte = 1;
if (prod != null) {
TableCellEditor editor = table.getCellEditor();
if ( editor!=null ) editor.stopCellEditing();
String tab[] = prod.split("&");
if (liste.containsKey(tab[0])) {
qte = qte + 1;
String value = tab[0] + "&" + tab[1] + "&" + qte;
liste.remove(tab[0]);
liste.put(tab[0], value);
} else {
qte = 1;
String value = tab[0] + "&" + tab[1] + "&" + qte;
liste.put(tab[0], value);
}
actualiser();
}
}
public void actualiser() {
mod.setNumRows(0);
Enumeration en = liste.elements();
while (en.hasMoreElements()) {
String value = (String) en.nextElement();
String[] tab = value.split("&");
Object data[] = {tab[0], tab[1], tab[2]};
mod.addRow(data);
}
mod.addRow(new Vector());
SwingUtilities.invokeLater(()->{
table.changeSelection(mod.getRowCount()-1, 0, false, false);
table.editCellAt(mod.getRowCount()-1, 0);
});
}
public static void main(String[] args) {
new Exo();
}
} |
Partager