Search code examples
javaswingjtablejcombobox

More Jcombo boxes related to one JTable


I have a question about JComboBox's and JTable.

In the project, I have 3 JComboBox's and a JTable and I want every time an item is selected from a JComboBox to put in my table some data from a database, but after I run the code I gave notice that only when I select an item from the first JComboBox, whom I have bound to the JTable first, data are available from the database.

My question is: I can bind only one JComboBox to a JTable?

I used the same code for all the 3 JComboBox.

package tutorial;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.*;
import java.sql.*;
import net.proteanit.sql.DbUtils;

public class Lista extends javax.swing.JFrame implements ActionListener, Runnable {
Connection conn;
public Lista() {
    initComponents();
    this.setSize(800,400);
    this.setResizable(false);  
}
// creates the components                    
private void initComponents() {
    bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
    tfSearch = new javax.swing.JTextField();
    bSearch = new javax.swing.JButton();
    lbAutor = new javax.swing.JLabel();
    cboxAutor = new javax.swing.JComboBox();
    cboxCategorie = new javax.swing.JComboBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    cboxLibrarie = new javax.swing.JComboBox();
    cbEditura = new javax.swing.JComboBox();
    lbCategorie = new javax.swing.JLabel();
    lbLibrarie = new javax.swing.JLabel();
    lbEditura = new javax.swing.JLabel();
    jLabel1 = new javax.swing.JLabel();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(null);
    tfSearch.setFont(new java.awt.Font("Arial Black", 1, 18)); // NOI18N
    tfSearch.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyReleased(java.awt.event.KeyEvent evt) {
            tfSearchKeyReleased(evt);
        }
    });
    getContentPane().add(tfSearch);
    tfSearch.setBounds(60, 40, 200, 30);
    bSearch.setBackground(new java.awt.Color(255, 255, 255));
    bSearch.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
    bSearch.setText("Search");
    bSearch.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bSearchActionPerformed(evt);
        }
    });
    getContentPane().add(bSearch);
    bSearch.setBounds(270, 40, 90, 30);
    lbAutor.setFont(new java.awt.Font("Arial Black", 3, 18)); // NOI18N
    lbAutor.setForeground(new java.awt.Color(255, 255, 255));
    lbAutor.setText("Autor:");
    getContentPane().add(lbAutor);
    lbAutor.setBounds(440, 120, 100, 20);
    cboxAutor.setBackground(new java.awt.Color(255, 153, 51));
    cboxAutor.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
    cboxAutor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Cristie", "Bronte", "Tolkien", "Meyer", "Van Vogt", "Pavel", "Inoue", "Austen", "Bromte", "Eminescu" }));
    cboxAutor.addItemListener(new java.awt.event.ItemListener() {
        public void itemStateChanged(java.awt.event.ItemEvent evt) {
            cboxAutorItemStateChanged(evt);
        }
    });
    cboxAutor.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cboxAutorActionPerformed(evt);
        }
    });
    getContentPane().add(cboxAutor);
    cboxAutor.setBounds(560, 120, 220, 30);
    cboxCategorie.setBackground(new java.awt.Color(255, 153, 51));
    cboxCategorie.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
    cboxCategorie.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Literatura de Dragoste", "Literatura Fantastica", "Literatura Politista", "Literatura SF", "Literatura Psihologica" }));
    org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTable1, org.jdesktop.beansbinding.ELProperty.create("mesajjjjj"), cboxCategorie, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
    bindingGroup.addBinding(binding);
    cboxCategorie.addItemListener(new java.awt.event.ItemListener() {
        public void itemStateChanged(java.awt.event.ItemEvent evt) {
            cboxCategorieItemStateChanged(evt);
        }
    });
    cboxCategorie.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cboxCategorieActionPerformed(evt);
        }
    });
    getContentPane().add(cboxCategorie);
    cboxCategorie.setBounds(560, 240, 220, 30);
    jTable1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 204, 204), 1, true));
    jTable1.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
        },
        new String [] {
        }
    ));
    jTable1.setDoubleBuffered(true);
    jScrollPane1.setViewportView(jTable1);
    getContentPane().add(jScrollPane1);
    jScrollPane1.setBounds(60, 100, 340, 230);
    cboxLibrarie.setBackground(new java.awt.Color(255, 153, 51));
    cboxLibrarie.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
    cboxLibrarie.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Librarium", "Humanitas", "Carturesti", "Alpha", "Diverta", "Pheonix" }));
    cboxLibrarie.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cboxLibrarieActionPerformed(evt);
        }
    });
    getContentPane().add(cboxLibrarie);
    cboxLibrarie.setBounds(560, 200, 220, 30);
    cbEditura.setBackground(new java.awt.Color(255, 153, 51));
    cbEditura.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
    cbEditura.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Corint-Junior", "Gramar", "Albastra", "Teora", "Mega", "Mediamira", "U.T. PRESS" }));
    cbEditura.addItemListener(new java.awt.event.ItemListener() {
        public void itemStateChanged(java.awt.event.ItemEvent evt) {
            cbEdituraItemStateChanged(evt);
        }
    });
    cbEditura.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cbEdituraActionPerformed(evt);
        }
    });
    getContentPane().add(cbEditura);
    cbEditura.setBounds(560, 160, 220, 30);
    lbCategorie.setFont(new java.awt.Font("Arial Black", 3, 18)); // NOI18N
    lbCategorie.setForeground(new java.awt.Color(255, 255, 255));
    lbCategorie.setText("Categorie:");
    getContentPane().add(lbCategorie);
    lbCategorie.setBounds(440, 240, 120, 30);
    lbLibrarie.setFont(new java.awt.Font("Arial Black", 3, 18)); // NOI18N
    lbLibrarie.setForeground(new java.awt.Color(255, 255, 255));
    lbLibrarie.setText("Librarie:");
    getContentPane().add(lbLibrarie);
    lbLibrarie.setBounds(440, 200, 120, 30);
    lbEditura.setFont(new java.awt.Font("Arial Black", 3, 18)); // NOI18N
    lbEditura.setForeground(new java.awt.Color(255, 255, 255));
    lbEditura.setText("Editura:");
    getContentPane().add(lbEditura);
    lbEditura.setBounds(440, 160, 130, 30);
    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/lis.jpg"))); // NOI18N
    getContentPane().add(jLabel1);
    jLabel1.setBounds(0, 0, 790, 370);
    bindingGroup.bind();
    pack();
}// </editor-fold> 
//end initComponents


private void cboxLibrarieItemStateChanged(java.awt.event.ActionEvent evt) {                                             

    try{
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost/proiectibd";
        conn =DriverManager.getConnection(url, "root", "");
        String sql;
        sql = "select Titlul_cartii,Data_publicatie,Pret from carte,librarie,arhiva where librarie.idLibrarie=arhiva.librarie_idLibrarie and carte.idCarte=arhiva.Carte_idCarte and nume_librarie=?";
        PreparedStatement ps;
        ps = conn.prepareStatement(sql);
        ps.setString(1,(String)cboxAutor.getSelectedItem());
        ResultSet rs=ps.executeQuery();
        jTable1.setModel(DbUtils.resultSetToTableModel (rs));
    }
    catch(Exception e){
        //JOptionPane.showMessageDialog(null,e);
    }
}                                            

//only this JComboBox works
private void cboxAutorItemStateChanged(java.awt.event.ItemEvent evt) {    
    try{
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost/proiectibd";
        conn =DriverManager.getConnection(url, "root", "");
        String sql;
        sql = "select Titlul_cartii,Data_publicatie,Pret from carte,autor where carte.autor_idautor=autor.idAutor and Nume_Autor=?";
        PreparedStatement ps;
        ps = conn.prepareStatement(sql);
        ps.setString(1,cboxAutor.getSelectedItem().toString());
        ResultSet rs=ps.executeQuery();
        jTable1.setModel(DbUtils.resultSetToTableModel (rs));
    }
    catch(Exception e){
        //JOptionPane.showMessageDialog(null,e);
    }
}                   

private void cbEdituraItemStateChanged(java.awt.event.ItemEvent evt) {                                           
    try{
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost/proiectibd";
        conn4 =DriverManager.getConnection(url, "root", "");
        String sql;
        sql = "select Titlul_cartii,Data_publicatie,Pret from carte,editura,contact where editura.ideditura=contact.editura_ideditura and carte.idCarte=contact.Carte_idCarte and nume_editura=?";
        PreparedStatement ps;
        ps = conn4.prepareStatement(sql);
        ps.setString(1,cboxAutor.getSelectedItem().toString());
        ResultSet rs=ps.executeQuery();
        jTable1.setModel(DbUtils.resultSetToTableModel (rs));
    }
    catch(Exception e){
        //JOptionPane.showMessageDialog(null,e);
    }
}                                          

private void cboxCategorieItemStateChanged(java.awt.event.ItemEvent evt) {                                               
    try{
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost/proiectibd";
        conn =DriverManager.getConnection(url, "root", "");
        String sql;
        sql = "select Titlul_cartii,Data_publicatie,Pret from carte,categorii where carte.Categorii_idCategorii=categorii.idCategorii and Nume_categorie=?";
        PreparedStatement ps;
        ps = conn.prepareStatement(sql);
        ps.setString(1,cboxAutor.getSelectedItem().toString());
        ResultSet rs=ps.executeQuery();
        jTable1.setModel(DbUtils.resultSetToTableModel (rs));

    }

    catch(Exception e){
        //JOptionPane.showMessageDialog(null,e);
    }
}  

// Variables declaration - do not modify                     
private javax.swing.JButton bSearch;
private javax.swing.JComboBox cbEditura;
private javax.swing.JComboBox cboxAutor;
private javax.swing.JComboBox cboxCategorie;
private javax.swing.JComboBox cboxLibrarie;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JLabel lbAutor;
private javax.swing.JLabel lbCategorie;
private javax.swing.JLabel lbEditura;
private javax.swing.JLabel lbLibrarie;
private javax.swing.JTextField tfSearch;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration                   

@Override
public void actionPerformed(ActionEvent e) {
    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void run() {
    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}

Solution

  • Okay, lets try and go through this systematically...

    Null Layouts...

    Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

    KeyListener on text components...

    There is never a really good reason to put a KeyListeners on text component. If you want to know when the field is updated, use a DocumentListener instead; if you want to modify/filter what the user is entering the field, then use a DocumentFilter; if you want to know when the user presses the Enter key, then use an ActionListener.

    You current approach is also really unhealthy, trying to perform a new request each time a key is released could cause your program to freeze or stutter as the request is made, it is also perform unnecessary requests.

    Instead, use a combination of a DocumentListener to detect the changes to the field and a javax.swing.Timer to inject a small delay between updates, restarting the timer each time the DocumentListener is notified of a change. Once the timer actually triggers, then you should perform the request.

    Combobox updates...

    It seems like you've copied and pasted your code, because in the cboxLibrarieItemStateChanged, cbEdituraItemStateChanged and cboxCategorieItemStateChanged methods, you are using the value from cboxAutor...

    ps.setString(1,cboxAutor.getSelectedItem().toString());
    

    You need to be using the correct combobox for the field you are trying to search...

    Resource Management

    You are not managing your resources well, leaving connections and other database resources open which could degrade performance over time...

    Since Java 7, it's become pretty easy to manage...

    try{
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost/proiectibd";
        try (Connection conn = DriverManager.getConnection(url, "root", "")) {
            String sql = "select Titlul_cartii,Data_publicatie,Pret from carte,autor where carte.autor_idautor=autor.idAutor and Nume_Autor=?";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1,cboxAutor.getSelectedItem().toString());
                try (ResultSet rs=ps.executeQuery()) {
                    jTable1.setModel(DbUtils.resultSetToTableModel (rs));
                }
            }
        }
    } catch(SQLException e){
        e.printStackTrace();// At the very least...
        //JOptionPane.showMessageDialog(null,e);
    }
    

    See The try-with-resources Statement for more details.