Uso de db4o en Java

| 2013-07-15 | 0 Comments

Una base de datos orientada a objetos es una base de datos donde los elementos son objetos. 

Un SBDOO extiende los lenguajes con datos persistentes de forma transparente, control de concurrencia, recuperación de datos, consultas asociativas y otras capacidades.
El objetivo de una base de datos orientada a objetos son los mismos que los de las bases de datos tradicionales, pero con la ventaja de representar los modelos de datos con un marco mucho más eficiente, manteniendo la integridad y relación entre ellos.

Acerca de db4o: Se utiliza en algunas de las compañías más grandes del mundo incluyendo a BMW, Hertz, y Bosch. db4objects es una compañía de bienes privados ubicada en San Mateo, California y soportada por inversores de Silicon Valley reconocidos como Mark Leslie, CEO fundador de Veritas, quien actúa como presidente en la actualidad.

Caso práctico: (Sistema simple para una Terminal de Ómnibus)

Antes que todo, agregar el .jar de db4o a su proyecto, en mi caso utilizo ECLIPSE JAVA SE.

terminal

Paso 1: Crear las clases necesarias (Sería como un mapeo que hay que hacer para que los objetos sean persistentes).

– Clase Control.java:

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
public class Control{
 
 private int id;
 private String salida;
 private String dia;
 private String empresa;
 private String terminalsal;
 private String terminaldes;
 
 public Control(int id, String sal, String dia, String des, String emp, String ter){
 this.id=id;
 this.salida = sal;
 this.dia= dia;
 this.setTerminaldes(des);
 this.empresa = emp;
 this.setTerminalsal(ter);
 }
 
 public String getDia() {
 return dia;
 }
 public void setDia(String dia) {
 this.dia = dia;
 }
 public String getSalida() {
 return salida;
 }
 public void setSalida(String salida) {
 this.salida = salida;
 }
 public String getEmpresa() {
 return empresa;
 }
 public void setEmpresa(String empresa) {
 this.empresa = empresa;
 }
 
public String getTerminaldes() {
 return terminaldes;
 }
 
public void setTerminaldes(String terminaldes) {
 this.terminaldes = terminaldes;
 }
 
public String getTerminalsal() {
 return terminalsal;
 }
 
public void setTerminalsal(String terminalsal) {
 this.terminalsal = terminalsal;
 }
 
public int getId() {
 return id;
 }
 
public void setId(int id) {
 this.id = id;
 }
 
}

– Clase Empresas.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Empresas extends EmpresasGenerico{
 
 protected String ruc;
 
 //Constructor
 public Empresas(String name, String dir, String tel, String ruc){
 super(name, dir, tel);
 this.ruc=ruc;
 }
 
public void setRuc(String ruc) {
 this.ruc=ruc;
 
 }
 public String getRuc() {
 return ruc;
 }
 
}

– Clase Terminales.java:

1
2
3
4
5
6
7
8
public class Terminales extends EmpresasGenerico{
 
 //Constructor
 public Terminales(String name, String dir, String tel){
 super(name, dir, tel);
 }
 
}

– Clase EmpresasGenerico.java:

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
public class EmpresasGenerico {
 
 //Propiedades
 protected String nombre;
 protected String direccion;
 protected String telefono;
 
 //Constructor
 public EmpresasGenerico(String name, String dir, String tel){
 this.nombre = name;
 this.direccion= dir;
 this.telefono = tel;
 }
 
 //Métodos para acceder a nombre
 public void setNombre(String name){
 this.nombre = name;
 }
 public String getNombre(){
 return this.nombre;
 }
 
 //Métodos para acceder a dirección
 public void setDireccion(String dir){
 this.direccion= dir;
 }
 public String getDireccion(){
 return this.direccion;
 }
 
 //Métodos para acceder a teléfono
 public void setTelefono(String tel){
 this.telefono = tel;
 }
 public String getTelefono(){
 return this.telefono;
 }
 
}

Paso 2: Crear clase principal 

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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import java.awt.BorderLayout;
import java.awt.EventQueue;
 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
 
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
 
import Clases.*;
import data.DataConnection;
 
import Vistas.*;
 
//import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import javax.swing.JButton;
public class Principal extends JFrame {
 
 private ObjectContainer db = DataConnection.getInstance();
 private JPanel contentPane;
 
/**
 * Launch the application.
 */
 public static void main(String[] args) {
 EventQueue.invokeLater(new Runnable() {
 public void run() {
 try {
 Principal frame = new Principal();
 frame.setVisible(true);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 });
 }
 
/**
 * Create the frame.
 */
 public Principal() {
 addWindowListener(new WindowAdapter() {
 @Override
 public void windowClosing(WindowEvent e) {
 db.close();
 }
 });
 setTitle("Gesti\u00F3n de Terminal de \u00D3mnibus");
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 setBounds(100, 100, 523, 353);
 setLocationRelativeTo(null);
 
 JMenuBar menuBar = new JMenuBar();
 setJMenuBar(menuBar);
 
 JMenu mnNewMenu = new JMenu("Archivo");
 menuBar.add(mnNewMenu);
 
 JMenuItem mntmNewMenuItem = new JMenuItem("Salir");
 mntmNewMenuItem.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent arg0) {
 int res=JOptionPane.showConfirmDialog(null,"Estas seguro que desea salir??",".::Pregunta::.",JOptionPane.YES_NO_OPTION);
 if(res==0){
 db.close();
 System.exit(0);
 }
 }
 });
 mnNewMenu.add(mntmNewMenuItem);
 
 JMenuItem mntmNewMenuItem_1 = new JMenuItem("Acerca de");
 mntmNewMenuItem_1.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent arg0) {
 JOptionPane.showMessageDialog(null,"Gestión de Terminal de ómnibus v1.0.\n\nTodos los derechos reservados.",".::Acerca de::.",JOptionPane.INFORMATION_MESSAGE);
 }
 });
 menuBar.add(mntmNewMenuItem_1);
 contentPane = new JPanel();
 contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
 setContentPane(contentPane);
 contentPane.setLayout(null);
 
 JButton btnNewButton = new JButton("Terminales");
 btnNewButton.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 VTerminales age2= new VTerminales();
 age2.setVisible(true);
 }
 });
 btnNewButton.setBounds(40, 35, 148, 78);
 contentPane.add(btnNewButton);
 
 JButton btnEmpresas = new JButton("Empresas");
 btnEmpresas.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent arg0) {
 VEmpresas age= new VEmpresas();
 age.setVisible(true);
 }
 });
 btnEmpresas.setBounds(307, 35, 148, 78);
 contentPane.add(btnEmpresas);
 
 JButton btnControl = new JButton("Control");
 btnControl.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent arg0) {
 VControl age3= new VControl();
 age3.setVisible(true);
 }
 });
 btnControl.setBounds(173, 173, 148, 78);
 contentPane.add(btnControl);
 }
}

Paso 3: Crear clase que gestiona conexión con la db.

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
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;
 
public class DataConnection {
 
private static DataConnection INSTANCE = null;
 private final String PATH = "terminal.db4o";
 private static ObjectContainer db;
 
 
 
// Private constructor suppresses
 private DataConnection() {
 }
 
// Creador sincronizado para protegerse de posibles problemas multi-hilo
 // Otra prueba para evitar instanciación múltiple
 private synchronized static void createInstance() {
 if (INSTANCE == null) {
 INSTANCE = new DataConnection();
 INSTANCE.performConnection();
 }
 }
 
public static ObjectContainer getInstance() {
 if (INSTANCE == null)
 createInstance();
 return db;
 }
 
public void performConnection() {
 EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
 db = Db4oEmbedded.openFile(config, PATH);
 }
 
 public void closeConnection() {
 db.close();
 }
 
}

Paso 4: Crear vistas

– VControl.java:

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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
import java.awt.BorderLayout;
 
public class VControl extends JFrame {
 
private ObjectContainer db = DataConnection.getInstance();
 private JPanel contentPane;
 private JButton btnNuevo;
 private JButton btnGuardar;
 private JButton btnEliminar;
 private JButton btnActualizar;
 private JButton btnSalir;
 
private JTextField textField;
 
 //Modelo generico para JTable
 DefaultTableModel model;
 private JPanel panel;
 private JScrollPane scrollPane;
 private JTable table;
 private JTextField textField_4;
 private JLabel lblDia;
 private JLabel lblId_1;
 private JTextField textField_1;
 private JComboBox comboBox;
 private JComboBox comboBox_1;
 private JComboBox comboBox_2;
 private JComboBox comboBox_3;
 
 void LlenarCombos(){
 //Llenar combo de Empresas
 List<Empresas> ps = null;
 ps = db.query(Empresas.class);
 for (Empresas ter : ps) {
 comboBox_1.addItem(ter.getNombre());
 }
 //Llenar combo de Terminales
 List<Terminales> ps2 = null;
 ps2 = db.query(Terminales.class);
 for (Terminales ter : ps2) {
 comboBox_2.addItem(ter.getNombre());
 comboBox_3.addItem(ter.getNombre());
 }
 comboBox.setSelectedIndex(-1);
 comboBox_1.setSelectedIndex(-1);
 comboBox_2.setSelectedIndex(-1);
 comboBox_3.setSelectedIndex(-1);
 }
 
 //Función para insertar un nuevo registro
 void insertar(ObjectContainer e){
 Control ter3 = new Control(Integer.parseInt((textField.getText())),null,null,null,null,null);
 
 ObjectSet<Object> ter2 = db.queryByExample(ter3);
 if(ter2.size()==0)
 {
 try{
 Control ter = new Control(Integer.parseInt((textField.getText())),textField_1.getText(),(String)comboBox.getSelectedItem(),
 (String)comboBox_3.getSelectedItem(),(String)comboBox_1.getSelectedItem(),(String)comboBox_2.getSelectedItem());
 db.store(ter);
 db.commit();
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setText("");
 textField_1.setText("");
 textField_4.setText("");
 comboBox.setSelectedIndex(-1);
 comboBox_1.setSelectedIndex(-1);
 comboBox_2.setSelectedIndex(-1);
 comboBox_3.setSelectedIndex(-1);
 textField.setEnabled(false);
 textField_1.setEnabled(false);
 comboBox.setEnabled(false);
 comboBox_1.setEnabled(false);
 comboBox_2.setEnabled(false);
 comboBox_3.setEnabled(false);
 comboBox.setSelectedIndex(-1);
 comboBox_1.setSelectedIndex(-1);
 comboBox_2.setSelectedIndex(-1);
 comboBox_3.setSelectedIndex(-1);
 }catch (Db4oException ee) {
 JOptionPane.showMessageDialog(null,ee.getMessage());
 db.rollback();
 }
 }
 else{
 JOptionPane.showMessageDialog(null,"El id "+textField.getText()+" ya existe.");
 }
 }
 
 //Función para listar registros
 void listar (ObjectContainer e){
 String[] titulos = {"ID", "Horarios Salidas","Empresa", "T. Salida", "T. Destino", "Día"};
 try {
 //encabezados de la tabla
 model = new DefaultTableModel(null, titulos){
 @Override
 public boolean isCellEditable(int fila, int columna) {
 return false;//Le decimos que ninguna celda se puede editar directamente en la tabla
 }
 };
 TableRowSorter sorter = new TableRowSorter(model);
 table.setRowSorter(sorter);//Le decimos que la tabla se pueda ordenar (Haciendo clic en las columnas)
 //arreglo fila, para almacenar registros
 String[] fila = new String [6];
 
 List<Control> ps = null;
 
 if (textField_4.getText().equals("")) {//Si no hay nada
 ps = db.query(Control.class);
 }
 else
 {
 ps = db.query(new Predicate<Control>() {
 public boolean match(Control o) {
 return o.getTerminaldes().toLowerCase().contains(textField_4.getText().toLowerCase());//Convertimos a minúscula y comparamos
 }
 }, new QueryComparator<Control>() {
 public int compare(Control o1, Control o2) {
 return 0;
 }
 });
 
 }
 
for (Control ter : ps) {//Añadimos los registros a la tabla
 fila[0] = String.valueOf(ter.getId());
 fila[1] = ter.getSalida();
 fila[2] = ter.getEmpresa();
 fila[3] = ter.getTerminalsal();
 fila[4] = ter.getTerminaldes();
 fila[5] = ter.getDia();
 model.addRow(fila);
 }
 //Agrego el default model
 table.setModel(model);
 }catch (Exception e1){
 JOptionPane.showMessageDialog(null, e1);
 }
 }
 
 //Función para modificar un registro
 void modificar (ObjectContainer e, int id){
 try {
 ObjectSet le = e.queryByExample(new Clases.Control(id,null,null,null,null,null));
 Control ter = (Control)le.next();
 ter.setId(Integer.parseInt((textField.getText())));
 ter.setEmpresa((String)comboBox_1.getSelectedItem());
 ter.setSalida(textField_1.getText());
 ter.setTerminaldes((String)comboBox_3.getSelectedItem());
 ter.setTerminalsal((String)comboBox_2.getSelectedItem());
 ter.setDia((String)comboBox.getSelectedItem());
 db.store(ter);
 db.commit();
 listar(db);
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setText("");
 textField_1.setText("");
 textField_4.setText("");
 textField.setEnabled(false);
 textField_1.setEnabled(false);
 comboBox.setEnabled(false);
 comboBox_1.setEnabled(false);
 comboBox_2.setEnabled(false);
 comboBox_3.setEnabled(false);
 comboBox.setSelectedIndex(-1);
 comboBox_1.setSelectedIndex(-1);
 comboBox_2.setSelectedIndex(-1);
 comboBox_3.setSelectedIndex(-1);
 }catch (Db4oException ee) {
 JOptionPane.showMessageDialog(null,ee.getMessage());
 db.rollback();
 }
 }
 
 //Función para eliminar un registro
 void eliminar (ObjectContainer e){
 if(table.getSelectedRow()!=-1){
 int confirmado = JOptionPane.showConfirmDialog(null, "¿Desea eliminar "+table.getValueAt(table.getSelectedRow(), 0)+"?");
 if (JOptionPane.OK_OPTION == confirmado){
 try {
 int fila = table.getSelectedRow();
 int valor= (int) table.getValueAt(fila, 0);
 ObjectSet le = e.queryByExample(new Control(valor,null,null,null,null,null));
 Control ter = (Control)le.next();
 db.delete(ter);
 db.commit();
 listar(db);
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setText("");
 textField_1.setText("");
 textField_4.setText("");
 comboBox.setSelectedIndex(-1);
 comboBox_1.setSelectedIndex(-1);
 comboBox_2.setSelectedIndex(-1);
 comboBox_3.setSelectedIndex(-1);
 textField.setEnabled(false);
 textField_1.setEnabled(false);
 comboBox.setEnabled(false);
 comboBox_1.setEnabled(false);
 comboBox_2.setEnabled(false);
 comboBox_3.setEnabled(false);
 comboBox.setSelectedIndex(-1);
 comboBox_1.setSelectedIndex(-1);
 comboBox_2.setSelectedIndex(-1);
 comboBox_3.setSelectedIndex(-1);
 }catch (Db4oException ee) {
 JOptionPane.showMessageDialog(null,ee.getMessage());
 db.rollback();
 }
 }
 }
 else{
 JOptionPane.showMessageDialog(null,"Seleccione algún registro");
 }
 }
 
 /**
 * Launch the application.
 */
 
 public static void main(String[] args) {
 EventQueue.invokeLater(new Runnable() {
 public void run() {
 try {
 VControl frame = new VControl();
 frame.setVisible(true);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 });
 }
 
/**
 * Create the frame.
 */
 public VControl() {
 setTitle("Control");
 addWindowListener(new WindowAdapter() {
 @Override
 public void windowClosed(WindowEvent arg0) {
 }
 @Override
 public void windowClosing(WindowEvent e) {
 }
 @Override
 public void windowActivated(WindowEvent arg0) {
 }
 @Override
 public void windowOpened(WindowEvent arg0) {
 LlenarCombos();
 listar(db);
 }
 });
 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 setBounds(100, 100, 694, 367);
 setLocationRelativeTo(null);
 contentPane = new JPanel();
 contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
 setContentPane(contentPane);
 contentPane.setLayout(null);
 
 JLabel lblId = new JLabel("H. Salida");
 lblId.setBounds(232, 25, 66, 14);
 contentPane.add(lblId);
 
 textField = new JTextField();
 textField.setEnabled(false);
 textField.setBounds(66, 22, 136, 20);
 contentPane.add(textField);
 textField.setColumns(10);
 
 JLabel lblApellido = new JLabel("Empresa");
 lblApellido.setBounds(481, 28, 66, 14);
 contentPane.add(lblApellido);
 
 JButton btnNewButton = new JButton("Mostrar Todo");
 btnNewButton.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 textField_4.setText("");
 listar(db);
 }
 });
 btnNewButton.setBounds(349, 124, 112, 23);
 contentPane.add(btnNewButton);
 
 btnNuevo = new JButton("Nuevo");
 btnNuevo.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent arg0) {
 
textField_1.setText("");
 textField.requestFocus();
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(true);
 textField.setEnabled(true);
 textField_1.setEnabled(true);
 comboBox.setEnabled(true);
 comboBox_1.setEnabled(true);
 comboBox_2.setEnabled(true);
 comboBox_3.setEnabled(true);
 comboBox.setSelectedIndex(-1);
 comboBox_1.setSelectedIndex(-1);
 comboBox_2.setSelectedIndex(-1);
 comboBox_3.setSelectedIndex(-1);
 //Poner nuevo id automáticamente
 int id=0;
 List<Control> ps2 = null;
 ps2 = db.query(Control.class);
 for (Control ter : ps2) {
 id=ter.getId();
 }
 id++;
 textField.setText(String.valueOf(id));
 }
 });
 btnNuevo.setBounds(10, 296, 89, 23);
 contentPane.add(btnNuevo);
 
 btnGuardar = new JButton("Guardar");
 btnGuardar.setEnabled(false);
 btnGuardar.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 if(textField.getText().length()>0 && textField_1.getText().length()>0 && comboBox.getSelectedIndex()>=0 && comboBox_1.getSelectedIndex()>=0
 && comboBox_2.getSelectedIndex()>=0 && comboBox_3.getSelectedIndex()>=0
 && textField.getText().length()<50 && textField_1.getText().length()<50) {
 try {
 insertar(db);
 listar(db);
 }
 catch (Exception ex) {
 JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
 }
 }
 else{
 JOptionPane.showMessageDialog(null, "Complete corectamente todos los campos.","Error",JOptionPane.ERROR_MESSAGE);
 }
 }
 });
 btnGuardar.setBounds(156, 296, 89, 23);
 contentPane.add(btnGuardar);
 
 btnEliminar = new JButton("Eliminar");
 btnEliminar.setEnabled(false);
 btnEliminar.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 eliminar(db);
 }
 });
 btnEliminar.setBounds(297, 296, 103, 23);
 contentPane.add(btnEliminar);
 
 btnActualizar = new JButton("Actualizar");
 btnActualizar.setEnabled(false);
 btnActualizar.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent arg0) {
 if(textField.getText().length()>0 && textField_1.getText().length()>0 && comboBox.getSelectedIndex()>=0 && comboBox_1.getSelectedIndex()>=0
 && comboBox_2.getSelectedIndex()>=0 && comboBox_3.getSelectedIndex()>=0
 && textField.getText().length()<50 && textField_1.getText().length()<50) {
 try {
 modificar(db,Integer.parseInt(textField.getText()));
 }
 catch (Exception ex) {
 JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
 }
 }
 else{
 JOptionPane.showMessageDialog(null, "Complete corectamente todos los campos.","Error",JOptionPane.ERROR_MESSAGE);
 }
 }
 });
 btnActualizar.setBounds(436, 296, 103, 23);
 contentPane.add(btnActualizar);
 
 btnSalir = new JButton("Salir");
 btnSalir.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 dispose();
 }
 });
 btnSalir.setBounds(571, 296, 89, 23);
 contentPane.add(btnSalir);
 
 panel = new JPanel();
 panel.setBounds(10, 163, 650, 122);
 contentPane.add(panel);
 panel.setLayout(new BorderLayout(0, 0));
 
 scrollPane = new JScrollPane();
 scrollPane.addMouseListener(new MouseAdapter() {
 @Override
 public void mouseClicked(MouseEvent arg0) {
 
}
 });
 panel.add(scrollPane, BorderLayout.CENTER);
 
 table = new JTable();
 table.addMouseListener(new MouseAdapter() {
 @Override
 public void mouseClicked(MouseEvent arg0) {
 if (arg0.getButton() == 1) {
 int fila = table.getSelectedRow();
 int valor= Integer.parseInt((String)table.getValueAt(fila, 0));
 try {
 ObjectSet le = db.queryByExample(new Control(valor,null,null,null,null,null));
 if (le.hasNext())
 {
 Control ter= (Control)le.next();
 textField.setText(String.valueOf(ter.getId()));
 textField_1.setText(ter.getSalida());
 comboBox.setSelectedItem(ter.getDia());
 comboBox_1.setSelectedItem(ter.getEmpresa());
 comboBox_2.setSelectedItem(ter.getTerminalsal());
 comboBox_3.setSelectedItem(ter.getTerminaldes());
 btnEliminar.setEnabled(true);
 btnActualizar.setEnabled(true);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setEnabled(false);
 textField_1.setEnabled(true);
 comboBox.setEnabled(true);
 comboBox_1.setEnabled(true);
 comboBox_2.setEnabled(true);
 comboBox_3.setEnabled(true);
 }
 }
 catch (Exception ee) {
 System.out.println("No se encuentra id");
 }
 }
 }
 });
 table.setModel(new DefaultTableModel(
 new Object[][] {
 },
 new String[] {
 }
 ));
 scrollPane.setViewportView(table);
 
 JLabel lblRuc = new JLabel("T. Salida");
 lblRuc.setBounds(10, 69, 66, 14);
 contentPane.add(lblRuc);
 
 textField_4 = new JTextField();
 textField_4.addKeyListener(new KeyAdapter() {
 @Override
 public void keyReleased(KeyEvent arg0) {
 listar(db);
 }
 });
 textField_4.setColumns(10);
 textField_4.setBounds(186, 125, 136, 20);
 contentPane.add(textField_4);
 
 JLabel lblTLlegada = new JLabel("T.Destino");
 lblTLlegada.setBounds(232, 69, 66, 14);
 contentPane.add(lblTLlegada);
 
 comboBox = new JComboBox();
 comboBox.setEnabled(false);
 comboBox.setModel(new DefaultComboBoxModel(new String[] {"Lunes", "Martes", "Mi\u00E9rcoles", "Jueves", "Viernes", "S\u00E1bado", "Domingo"}));
 comboBox.setBounds(535, 63, 125, 20);
 contentPane.add(comboBox);
 
 comboBox_1 = new JComboBox();
 comboBox_1.setEnabled(false);
 comboBox_1.setBounds(535, 22, 125, 20);
 contentPane.add(comboBox_1);
 
 comboBox_2 = new JComboBox();
 comboBox_2.setEnabled(false);
 comboBox_2.setBounds(66, 66, 136, 20);
 contentPane.add(comboBox_2);
 
 lblDia = new JLabel("D\u00EDa");
 lblDia.setBounds(481, 69, 66, 14);
 contentPane.add(lblDia);
 
 comboBox_3 = new JComboBox();
 comboBox_3.setEnabled(false);
 comboBox_3.setBounds(301, 66, 134, 20);
 contentPane.add(comboBox_3);
 
 lblId_1 = new JLabel("ID");
 lblId_1.setBounds(10, 25, 46, 14);
 contentPane.add(lblId_1);
 
 textField_1 = new JTextField();
 textField_1.setEnabled(false);
 textField_1.setColumns(10);
 textField_1.setBounds(299, 22, 136, 20);
 contentPane.add(textField_1);
 }
}

– VEmpresas.java

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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import java.awt.BorderLayout;
 
public class VEmpresas extends JFrame {
 
private ObjectContainer db = DataConnection.getInstance();
 private JPanel contentPane;
 private JTextField textField_1;
 private JTextField textField_2;
 private JButton btnNuevo;
 private JButton btnGuardar;
 private JButton btnEliminar;
 private JButton btnActualizar;
 private JButton btnSalir;
 
private JTextField textField;
 
 //Modelo generico para JTable
 DefaultTableModel model;
 private JPanel panel;
 private JScrollPane scrollPane;
 private JTable table;
 private JTextField textField_3;
 private JTextField textField_4;
 
 //Función para insertar un nuevo registro
 void insertar(ObjectContainer e){
 Clases.Empresas ter3 = new Clases.Empresas(textField.getText(),null,null,null);
 ObjectSet<Object> ter2 = db.queryByExample(ter3);
 if(ter2.size()==0)
 {
 try{
 Clases.Empresas ter = new Clases.Empresas(textField.getText(),textField_1.getText(),textField_2.getText(),textField_3.getText());
 db.store(ter);
 db.commit();
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setText("");
 textField_1.setText("");
 textField_2.setText("");
 textField_3.setText("");
 textField_4.setText("");
 textField_1.setEnabled(false);
 textField_3.setEnabled(false);
 textField_2.setEnabled(false);
 textField.setEnabled(false);
 }catch (Db4oException ee) {
 JOptionPane.showMessageDialog(null,ee.getMessage());
 db.rollback();
 }
 }
 else{
 JOptionPane.showMessageDialog(null,"El nombre "+textField.getText()+" ya existe.");
 }
 }
 
 //Función para litar registros
 void listar (ObjectContainer e){
 String[] titulos = {"Nombre", "Dirección","Teléfono", "RUC"};
 try {
 //encabezados de la tabla
 model = new DefaultTableModel(null, titulos){
 @Override
 public boolean isCellEditable(int fila, int columna) {
 return false;//Le decimos que ninguna celda se puede editar directamente en la tabla
 }
 };
 TableRowSorter sorter = new TableRowSorter(model);
 table.setRowSorter(sorter);//Le decimos que la tabla se pueda ordenar (Haciendo clic en las columnas)
 //arreglo fila, para almacenar registros
 String[] fila = new String [4];
 
 List<Empresas> ps = null;
 
 if (textField_4.getText().equals("")) {//Si no hay nada
 ps = db.query(Empresas.class);
 }
 else
 {
 ps = db.query(new Predicate<Empresas>() {
 public boolean match(Empresas o) {
 return o.getNombre().toLowerCase().contains(textField_4.getText().toLowerCase());//Convertimos a minúscula y comparamos
 }
 }, new QueryComparator<Empresas>() {
 public int compare(Empresas o1, Empresas o2) {
 return 0;
 }
 });
 
 }
 
for (Empresas ter : ps) {//Añadimos los registros a la tabla
 fila[0] = ter.getNombre();
 fila[1] = ter.getDireccion();
 fila[2] = ter.getTelefono();
 fila[3] = ter.getRuc();
 model.addRow(fila);
 }
 //Agrego el default model
 table.setModel(model);
 }catch (Exception e1){
 JOptionPane.showMessageDialog(null, e1);
 }
 }
 
 //Función para modificar un registro
 void modificar (ObjectContainer e, String nombre){
 try {
 ObjectSet le = e.queryByExample(new Clases.Empresas(nombre,null,null,null));
 Clases.Empresas ter = (Clases.Empresas)le.next();
 ter.setNombre(textField.getText());
 ter.setDireccion((textField_1.getText()));
 ter.setTelefono((textField_2.getText()));
 ter.setRuc((textField_3.getText()));
 db.store(ter);
 db.commit();
 listar(db);
 textField.enable(false);
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setText("");
 textField_1.setText("");
 textField_2.setText("");
 textField_3.setText("");
 textField_4.setText("");
 textField_1.setEnabled(false);
 textField_3.setEnabled(false);
 textField_2.setEnabled(false);
 textField.setEnabled(false);
 }catch (Db4oException ee) {
 JOptionPane.showMessageDialog(null,ee.getMessage());
 db.rollback();
 }
 }
 
 //Función para eliminar un registro
 void eliminar (ObjectContainer e){
 if(table.getSelectedRow()!=-1){
 int confirmado = JOptionPane.showConfirmDialog(null, "¿Desea eliminar "+table.getValueAt(table.getSelectedRow(), 0)+"?");
 if (JOptionPane.OK_OPTION == confirmado){
 try {
 int fila = table.getSelectedRow();
 String valor= (String) table.getValueAt(fila, 0);
 ObjectSet le = e.queryByExample(new Clases.Empresas(valor,null,null,null));
 Clases.Empresas ter = (Clases.Empresas)le.next();
 db.delete(ter);
 db.commit();
 listar(db);
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setText("");
 textField_1.setText("");
 textField_2.setText("");
 textField_3.setText("");
 textField_4.setText("");
 textField_1.setEnabled(false);
 textField_3.setEnabled(false);
 textField_2.setEnabled(false);
 textField.setEnabled(false);
 }catch (Db4oException ee) {
 JOptionPane.showMessageDialog(null,ee.getMessage());
 db.rollback();
 }
 }
 }
 else{
 JOptionPane.showMessageDialog(null,"Seleccione algún registro");
 }
 }
 
 /**
 * Launch the application.
 */
 
 public static void main(String[] args) {
 EventQueue.invokeLater(new Runnable() {
 public void run() {
 try {
 VEmpresas frame = new VEmpresas();
 frame.setVisible(true);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 });
 }
 
/**
 * Create the frame.
 */
 public VEmpresas() {
 setTitle("Empresas");
 addWindowListener(new WindowAdapter() {
 @Override
 public void windowClosed(WindowEvent arg0) {
 }
 @Override
 public void windowClosing(WindowEvent e) {
 }
 @Override
 public void windowActivated(WindowEvent arg0) {
 }
 @Override
 public void windowOpened(WindowEvent e) {
 listar(db);
 }
 });
 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 setBounds(100, 100, 694, 367);
 setLocationRelativeTo(null);
 contentPane = new JPanel();
 contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
 setContentPane(contentPane);
 contentPane.setLayout(null);
 
 JLabel lblId = new JLabel("Nombre");
 lblId.setBounds(10, 25, 46, 14);
 contentPane.add(lblId);
 
 textField = new JTextField();
 textField.setEnabled(false);
 textField.setBounds(81, 22, 136, 20);
 contentPane.add(textField);
 textField.setColumns(10);
 
 textField_1 = new JTextField();
 textField_1.setEnabled(false);
 textField_1.setColumns(10);
 textField_1.setBounds(503, 25, 136, 20);
 contentPane.add(textField_1);
 
 JLabel lblApellido = new JLabel("Tel\u00E9fono");
 lblApellido.setBounds(10, 76, 66, 14);
 contentPane.add(lblApellido);
 
 textField_2 = new JTextField();
 textField_2.setEnabled(false);
 textField_2.setColumns(10);
 textField_2.setBounds(81, 73, 136, 20);
 contentPane.add(textField_2);
 
 JLabel lblNombre = new JLabel("Direcci\u00F3n");
 lblNombre.setBounds(424, 28, 74, 14);
 contentPane.add(lblNombre);
 
 JButton btnNewButton = new JButton("Mostrar Todo");
 btnNewButton.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 textField_4.setText("");
 listar(db);
 }
 });
 btnNewButton.setBounds(349, 124, 112, 23);
 contentPane.add(btnNewButton);
 
 btnNuevo = new JButton("Nuevo");
 btnNuevo.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent arg0) {
 textField.setText("");
 textField_1.setText("");
 textField_2.setText("");
 textField_3.setText("");
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(true);
 textField_1.setEnabled(true);
 textField_3.setEnabled(true);
 textField_2.setEnabled(true);
 textField.setEnabled(true);
 textField.requestFocus();
 }
 });
 btnNuevo.setBounds(10, 296, 89, 23);
 contentPane.add(btnNuevo);
 
 btnGuardar = new JButton("Guardar");
 btnGuardar.setEnabled(false);
 btnGuardar.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 if(textField.getText().length()>0 && textField_2.getText().length()>0 && textField_1.getText().length()>0
 && textField.getText().length()<50 && textField_2.getText().length()<50 && textField_1.getText().length()<50) {
 try {
 insertar(db);
 listar(db);
 }
 catch (Exception ex) {
 JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
 }
 }
 else{
 JOptionPane.showMessageDialog(null, "Complete corectamente todos los campos.","Error",JOptionPane.ERROR_MESSAGE);
 }
 }
 });
 btnGuardar.setBounds(156, 296, 89, 23);
 contentPane.add(btnGuardar);
 
 btnEliminar = new JButton("Eliminar");
 btnEliminar.setEnabled(false);
 btnEliminar.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 eliminar(db);
 }
 });
 btnEliminar.setBounds(297, 296, 103, 23);
 contentPane.add(btnEliminar);
 
 btnActualizar = new JButton("Actualizar");
 btnActualizar.setEnabled(false);
 btnActualizar.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent arg0) {
 if(textField.getText().length()>0 && textField_2.getText().length()>0 && textField_1.getText().length()>0
 && textField.getText().length()<50 && textField_2.getText().length()<50 && textField_1.getText().length()<50) {
 try {
 modificar(db,textField.getText());
 }
 catch (Exception ex) {
 JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
 }
 }
 else{
 JOptionPane.showMessageDialog(null, "Complete corectamente todos los campos.","Error",JOptionPane.ERROR_MESSAGE);
 }
 }
 });
 btnActualizar.setBounds(436, 296, 103, 23);
 contentPane.add(btnActualizar);
 
 btnSalir = new JButton("Salir");
 btnSalir.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 dispose();
 }
 });
 btnSalir.setBounds(571, 296, 89, 23);
 contentPane.add(btnSalir);
 
 panel = new JPanel();
 panel.setBounds(10, 163, 650, 122);
 contentPane.add(panel);
 panel.setLayout(new BorderLayout(0, 0));
 
 scrollPane = new JScrollPane();
 scrollPane.addMouseListener(new MouseAdapter() {
 @Override
 public void mouseClicked(MouseEvent arg0) {
 
}
 });
 panel.add(scrollPane, BorderLayout.CENTER);
 
 table = new JTable();
 table.addMouseListener(new MouseAdapter() {
 @Override
 public void mouseClicked(MouseEvent arg0) {
 if (arg0.getButton() == 1) {
 int fila = table.getSelectedRow();
 String valor=(String) table.getValueAt(fila, 0);
 try {
 ObjectSet le = db.queryByExample(new Clases.Empresas(valor,null,null,null));
 if (le.hasNext())
 {
 Clases.Empresas ter = (Clases.Empresas)le.next();
 textField.setText(ter.getNombre());
 textField_1.setText(ter.getDireccion());
 textField_2.setText(ter.getTelefono());
 textField_3.setText(ter.getRuc());
 btnEliminar.setEnabled(true);
 btnActualizar.setEnabled(true);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setEnabled(false);
 textField_1.setEnabled(true);
 textField_3.setEnabled(true);
 textField_2.setEnabled(true);
 }
 }
 catch (Exception ee) {
 System.out.println("No se encuentra nombre");
 }
 }
 }
 });
 table.setModel(new DefaultTableModel(
 new Object[][] {
 },
 new String[] {
 }
 ));
 scrollPane.setViewportView(table);
 
 JLabel lblRuc = new JLabel("RUC");
 lblRuc.setBounds(424, 73, 66, 14);
 contentPane.add(lblRuc);
 
 textField_3 = new JTextField();
 textField_3.setEnabled(false);
 textField_3.setColumns(10);
 textField_3.setBounds(503, 73, 136, 20);
 contentPane.add(textField_3);
 
 textField_4 = new JTextField();
 textField_4.addKeyListener(new KeyAdapter() {
 @Override
 public void keyReleased(KeyEvent arg0) {
 listar(db);
 }
 });
 textField_4.setColumns(10);
 textField_4.setBounds(186, 125, 136, 20);
 contentPane.add(textField_4);
 }
}

– VTerminales.java

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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import java.awt.BorderLayout;
 
public class VTerminales extends JFrame {
 
private ObjectContainer db = DataConnection.getInstance();
 private JPanel contentPane;
 private JTextField textField_1;
 private JTextField textField_2;
 private JButton btnNuevo;
 private JButton btnGuardar;
 private JButton btnEliminar;
 private JButton btnActualizar;
 private JButton btnSalir;
 
private JTextField textField;
 
 //Modelo generico para JTable
 DefaultTableModel model;
 private JPanel panel;
 private JScrollPane scrollPane;
 private JTable table;
 private JTextField txtEn;
 
 //Función para insertar un nuevo registro
 void insertar(ObjectContainer e){
 Clases.Terminales ter3 = new Clases.Terminales(textField.getText(),null,null);
 ObjectSet<Object> ter2 = db.queryByExample(ter3);
 if(ter2.size()==0)
 {
 try{
 Clases.Terminales ter = new Clases.Terminales(textField.getText(),textField_1.getText(),textField_2.getText());
 db.store(ter);
 db.commit();
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setEnabled(false);
 textField_1.setEnabled(false);
 textField_2.setEnabled(false);
 textField.setText("");
 textField_1.setText("");
 textField_2.setText("");
 txtEn.setText("");
 }catch (Db4oException ee) {
 JOptionPane.showMessageDialog(null,ee.getMessage());
 db.rollback();
 }
 }
 else{
 JOptionPane.showMessageDialog(null,"El nombre "+textField.getText()+" ya existe.");
 }
 }
 
 //Función para litar registros
 void listar (ObjectContainer e){
 String[] titulos = {"Nombre", "Dirección","Teléfono"};
 try {
 //encabezados de la tabla
 model = new DefaultTableModel(null, titulos){
 @Override
 public boolean isCellEditable(int fila, int columna) {
 return false;//Le decimos que ninguna celda se puede editar directamente en la tabla
 }
 };
 TableRowSorter sorter = new TableRowSorter(model);
 table.setRowSorter(sorter);//Le decimos que la tabla se pueda ordenar (Haciendo clic en las columnas)
 //arreglo fila, para almacenar registros
 String[] fila = new String [3];
 
 List<Terminales> ps = null;
 
 if (txtEn.getText().equals("")) {//Si no hay nada
 ps = db.query(Terminales.class);
 }
 else
 {
 ps = db.query(new Predicate<Terminales>() {
 public boolean match(Terminales o) {
 return o.getNombre().toLowerCase().contains(txtEn.getText().toLowerCase());//Convertimos a minúscula y comparamos
 }
 }, new QueryComparator<Terminales>() {
 public int compare(Terminales o1, Terminales o2) {
 return 0;
 }
 });
 
 }
 
for (Terminales ter : ps) {//Añadimos los registros a la tabla
 fila[0] = ter.getNombre();
 fila[1] = ter.getDireccion();
 fila[2] = ter.getTelefono();
 model.addRow(fila);
 }
 //Agrego el default model
 table.setModel(model);
 }catch (Exception e1){
 JOptionPane.showMessageDialog(null, e1);
 }
 }
 
 //Función para modificar un registro
 void modificar (ObjectContainer e, String nombre){
 try {
 ObjectSet le = e.queryByExample(new Clases.Terminales(nombre,null,null));
 Clases.Terminales ter = (Clases.Terminales)le.next();
 ter.setNombre(textField.getText());
 ter.setDireccion((textField_1.getText()));
 ter.setTelefono((textField_2.getText()));
 db.store(ter);
 db.commit();
 listar(db);
 textField.enable(false);
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setEnabled(false);
 textField_1.setEnabled(false);
 textField_2.setEnabled(false);
 textField.setText("");
 textField_1.setText("");
 textField_2.setText("");
 txtEn.setText("");
 }catch (Db4oException ee) {
 JOptionPane.showMessageDialog(null,ee.getMessage());
 db.rollback();
 }
 }
 
 //Función para eliminar un registro
 void eliminar (ObjectContainer e){
 if(table.getSelectedRow()!=-1){
 int confirmado = JOptionPane.showConfirmDialog(null, "¿Desea eliminar "+table.getValueAt(table.getSelectedRow(), 0)+"?");
 if (JOptionPane.OK_OPTION == confirmado){
 try {
 int fila = table.getSelectedRow();
 String valor= (String) table.getValueAt(fila, 0);
 ObjectSet le = e.queryByExample(new Clases.Terminales(valor,null,null));
 Clases.Terminales ter = (Clases.Terminales)le.next();
 db.delete(ter);
 db.commit();
 listar(db);
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setEnabled(false);
 textField_1.setEnabled(false);
 textField_2.setEnabled(false);
 textField.setText("");
 textField_1.setText("");
 textField_2.setText("");
 txtEn.setText("");
 }catch (Db4oException ee) {
 JOptionPane.showMessageDialog(null,ee.getMessage());
 db.rollback();
 }
 }
 }
 else{
 JOptionPane.showMessageDialog(null,"Seleccione algún registro");
 }
 }
 
 /**
 * Launch the application.
 */
 
 public static void main(String[] args) {
 EventQueue.invokeLater(new Runnable() {
 public void run() {
 try {
 VTerminales frame = new VTerminales();
 frame.setVisible(true);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 });
 }
 
/**
 * Create the frame.
 */
 public VTerminales() {
 setTitle("Terminales");
 addWindowListener(new WindowAdapter() {
 @Override
 public void windowClosed(WindowEvent arg0) {
 }
 @Override
 public void windowClosing(WindowEvent e) {
 }
 @Override
 public void windowActivated(WindowEvent e) {
 }
 @Override
 public void windowOpened(WindowEvent e) {
 listar(db);
 }
 });
 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 setBounds(100, 100, 694, 367);
 setLocationRelativeTo(null);
 contentPane = new JPanel();
 contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
 setContentPane(contentPane);
 contentPane.setLayout(null);
 
 JLabel lblId = new JLabel("Nombre");
 lblId.setBounds(10, 25, 46, 14);
 contentPane.add(lblId);
 
 textField = new JTextField();
 textField.setEnabled(false);
 textField.setBounds(66, 22, 136, 20);
 contentPane.add(textField);
 textField.setColumns(10);
 
 textField_1 = new JTextField();
 textField_1.setEnabled(false);
 textField_1.setColumns(10);
 textField_1.setBounds(503, 25, 136, 20);
 contentPane.add(textField_1);
 
 JLabel lblApellido = new JLabel("Tel\u00E9fono");
 lblApellido.setBounds(208, 69, 66, 14);
 contentPane.add(lblApellido);
 
 textField_2 = new JTextField();
 textField_2.setEnabled(false);
 textField_2.setColumns(10);
 textField_2.setBounds(279, 66, 136, 20);
 contentPane.add(textField_2);
 
 JLabel lblNombre = new JLabel("Direcci\u00F3n");
 lblNombre.setBounds(424, 28, 74, 14);
 contentPane.add(lblNombre);
 
 JButton btnNewButton = new JButton("Mostrar Todo");
 btnNewButton.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 listar(db);
 txtEn.setText("");
 }
 });
 btnNewButton.setBounds(355, 121, 112, 23);
 contentPane.add(btnNewButton);
 
 btnNuevo = new JButton("Nuevo");
 btnNuevo.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent arg0) {
 textField.setText("");
 textField.setEnabled(true);
 textField_1.setEnabled(true);
 textField_2.setEnabled(true);
 textField_1.setText("");
 textField_2.setText("");
 textField.requestFocus();
 btnEliminar.setEnabled(false);
 btnActualizar.setEnabled(false);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(true);
 }
 });
 btnNuevo.setBounds(10, 296, 89, 23);
 contentPane.add(btnNuevo);
 
 btnGuardar = new JButton("Guardar");
 btnGuardar.setEnabled(false);
 btnGuardar.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 if(textField.getText().length()>0 && textField_2.getText().length()>0 && textField_1.getText().length()>0
 && textField.getText().length()<50 && textField_2.getText().length()<50 && textField_1.getText().length()<50) {
 try {
 insertar(db);
 listar(db);
 }
 catch (Exception ex) {
 JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
 }
 }
 else{
 JOptionPane.showMessageDialog(null, "Complete corectamente todos los campos.","Error",JOptionPane.ERROR_MESSAGE);
 }
 }
 });
 btnGuardar.setBounds(156, 296, 89, 23);
 contentPane.add(btnGuardar);
 
 btnEliminar = new JButton("Eliminar");
 btnEliminar.setEnabled(false);
 btnEliminar.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 eliminar(db);
 }
 });
 btnEliminar.setBounds(297, 296, 103, 23);
 contentPane.add(btnEliminar);
 
 btnActualizar = new JButton("Actualizar");
 btnActualizar.setEnabled(false);
 btnActualizar.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent arg0) {
 if(textField.getText().length()>0 && textField_2.getText().length()>0 && textField_1.getText().length()>0
 && textField.getText().length()<50 && textField_2.getText().length()<50 && textField_1.getText().length()<50) {
 try {
 modificar(db,textField.getText());
 }
 catch (Exception ex) {
 JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
 }
 }
 else{
 JOptionPane.showMessageDialog(null, "Complete corectamente todos los campos.","Error",JOptionPane.ERROR_MESSAGE);
 }
 }
 });
 btnActualizar.setBounds(436, 296, 103, 23);
 contentPane.add(btnActualizar);
 
 btnSalir = new JButton("Salir");
 btnSalir.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 dispose();
 }
 });
 btnSalir.setBounds(571, 296, 89, 23);
 contentPane.add(btnSalir);
 
 panel = new JPanel();
 panel.setBounds(10, 163, 650, 122);
 contentPane.add(panel);
 panel.setLayout(new BorderLayout(0, 0));
 
 scrollPane = new JScrollPane();
 scrollPane.addMouseListener(new MouseAdapter() {
 @Override
 public void mouseClicked(MouseEvent arg0) {
 
}
 });
 panel.add(scrollPane, BorderLayout.CENTER);
 
 table = new JTable();
 
table.addMouseListener(new MouseAdapter() {
 @Override
 public void mouseClicked(MouseEvent arg0) {
 if (arg0.getButton() == 1) {
 int fila = table.getSelectedRow();
 String valor=(String) table.getValueAt(fila, 0);
 try {
 ObjectSet le = db.queryByExample(new Clases.Terminales(valor,null,null));
 if (le.hasNext())
 {
 Clases.Terminales ter = (Clases.Terminales)le.next();
 textField.setText(ter.getNombre());
 textField_1.setText(ter.getDireccion());
 textField_2.setText(ter.getTelefono());
 btnEliminar.setEnabled(true);
 btnActualizar.setEnabled(true);
 btnNuevo.setEnabled(true);
 btnGuardar.setEnabled(false);
 textField.setEnabled(false);
 textField_1.setEnabled(true);
 textField_2.setEnabled(true);
 }
 }
 catch (Exception ee) {
 System.out.println("No se encuentra nombre");
 }
 }
 }
 });
 table.setModel(new DefaultTableModel(
 new Object[][] {
 },
 new String[] {
 }
 ));
 scrollPane.setViewportView(table);
 
 txtEn = new JTextField();
 txtEn.addKeyListener(new KeyAdapter() {
 @Override
 public void keyReleased(KeyEvent arg0) {
 listar(db);
 }
 });
 txtEn.setColumns(10);
 txtEn.setBounds(180, 122, 136, 20);
 contentPane.add(txtEn);
 }
 
}

 Dejo el source code del ejemplo (Proyecto Eclipse – Java SE):

github-logo

 

 

 

 

Si tienen alguna duda, no duden en hacérmela.

Acerca del autor: Rodrigo Paszniuk

Ingeniero Informático, amante de la tecnología, la música, el ciclismo y aprender cosas nuevas.

Posts Relacionados

  • Electron, framework Javascript para crear aplicaciones de escritorio
  • JSF 2 con Maven – Hola Mundo
  • Java RMI
  • Gestión de cambios de la base de datos – Liquibase



SEGUÍNOS EN FACEBOOK


GITHUB