Ver Mensaje Individual
  #2 (permalink)  
Antiguo 28/07/2015, 11:55
Avatar de GusGarsaky
GusGarsaky
 
Fecha de Ingreso: febrero-2015
Mensajes: 33
Antigüedad: 9 años, 2 meses
Puntos: 2
Respuesta: Conectar con base de datos y mostrar registros

Esta clase representa tu tabla categoría:

Código Java:
Ver original
  1. public class Category {
  2.    
  3.     private long id;
  4.     private String name;
  5.     private List<Meal> meals;
  6.  
  7.     // constructores, getters y setters
  8. }

Esta tabla representa a tu tabla platillo:

Código Java:
Ver original
  1. public class Meal {
  2.  
  3.     private long id;
  4.     private String name;
  5.     private float price;
  6.  
  7.     // constructores, getters y setters
  8.  
  9. }

Esta es una capa de abstracción, es un DAO (Data Access Object - objeto de acceso a datos) que se usa para separar lógica de modelo del resto de la aplicación.

Código Java:
Ver original
  1. public interface RestauranteDao {
  2.    
  3.     public List<Category> getAllCategories() {
  4.         List<Category> categories = new ArrayList<>();
  5.         String sql = "SELECT * FROM categories";
  6.  
  7.         try (Connection con = Connection.getConnection();
  8.                  Statement st = con.createStatement(sql)) {
  9.  
  10.             // hace la consulta
  11.             ResultSet rs = con.executeQuery();
  12.  
  13.             while(rs.next()) {
  14.                 Category category = new Category();
  15.                 category.setId(rs.getInt("id"));
  16.                 category.setName(rs.getString("name");
  17.                 categories.add(category);
  18.             }
  19.         } catch(SQLException e) {
  20.                 // hacer algo con la excepcion
  21.         }
  22.  
  23.         return categories;
  24.     }
  25.  
  26.     public List<Meal> getMealsByCategory(int categoryId) {
  27.         List<Meal> meals = new ArrayList<>();
  28.         String sql = "SELECT * FROM meals WHERE category_id = ?";
  29.  
  30.         try (Connection con = Connection.getConnection();
  31.                  PrepareStatement pst = con.prepareStatement(sql)) {
  32.  
  33.             // bindea los datos a la consulta
  34.             pst.setInt(1, categoryId);
  35.             // hace la consulta
  36.             ResultSet rs = con.executeQuery();
  37.  
  38.             while(rs.next()) {
  39.                 Meal meal = new Meal();
  40.                 meal.setId(rs.getInt("id"));
  41.                 meal.setName(rs.getString("name"));
  42.                 meal.setName(rs.getFloat("price"));
  43.                 meals.add(meal);
  44.             }
  45.         } catch(SQLException e) {
  46.                 // hacer algo con la excepcion
  47.         }
  48.  
  49.         return meals;
  50.     }
  51.  
  52.     public List<Meal> getMealsByCategoryName(String categoryName) {
  53.         List<Meal> meals = new ArrayList<>();
  54.         String sql = "SELECT Id FROM category WHERE name = ?";
  55.  
  56.         try (Connection con = Connection.getConnection();
  57.                  PrepareStatement pst = con.prepareStatement(sql)) {
  58.            
  59.             // id de la categoria
  60.             int categoryId;
  61.             // bindea los datos a la consulta
  62.             pst.setString(1, categoryName);
  63.             // hace la consulta
  64.             ResultSet rs = con.executeQuery();
  65.  
  66.             while(rs.next()) {
  67.                 categoryId = rs.getInt("id");
  68.             }
  69.  
  70.             meals = this.getMealsByCategoryId(categoryId);
  71.         } catch(SQLException e) {
  72.                 // hacer algo con la excepcion
  73.         }
  74.  
  75.         return meals;
  76.     }
  77.  
  78. }

Y aquí utilizamos lo anterior:

Código Java:
Ver original
  1. listCategories.addSelectionListener(new ListSelectionListener() {
  2.  
  3.     @Override
  4.     public void valueChanged(ListSelectionEvent e) {
  5.         if(!e.getValueIsAdjusting()) {
  6.             RestaurantDao dao = new RestaurantDao();
  7.             // jlist origen del evento
  8.             JList target = (JList) e.getSource();
  9.             // index seleccionado en la lista
  10.             int indexSelected = target.getSelectedIndex();
  11.             // obtiene el listmodel y obtiene el objeto Category por index
  12.             Category category = target.getSelectionModel().get(indexSelected);
  13.             // obtiene la lista de platillos de acuerdo a la categoria
  14.             List<Meal> meals = dao.getMealsByCategory(category.getId());
  15.            
  16.             // lo pasas a la tabla...
  17.         }
  18.     }
  19. });

Una vez que ya tienes los platillos, pasarlos al JTable no tiene mayor misterio. Si tienes una duda con eso, la comentas.

PD: Agrega al JList un ListModel, así trabajas siempre con objetos:

Código Java:
Ver original
  1. RestaurantDao dao = new RestaurantDao();
  2. List<Category> categories = dao.getAllCategories();
  3. ListModel<Category> model = new DefaultListModel<>();
  4.  
  5. for(Category category : categories) {
  6.     model.addElement(model);
  7. }
  8.  
  9. JList listCategories = new JList(model);