Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        4年前关闭。
                                                                                            
                
        
我对JComboBoxJTable有疑问。

在项目中,我有3个JComboBox和一个JTable,我希望每次从JComboBox中选择一个项目以将数据库中的某些数据放入表中,但是在运行代码后,我给出了请注意,只有当我从第一个JComboBox绑定到第一个JTable的项目中选择一个项目时,数据库中的数据才可用。

我的问题是:我只能将一个JComboBox绑定到JTable吗?

我对所有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.
}
}

最佳答案

好吧,让我们尝试系统地进行一下...

空布局...

避免使用null布局,像素完美布局是现代ui设计中的一种幻觉。有太多因素会影响组件的单个大小,您无法控制。 Swing旨在与布局经理为核心一起工作,舍弃这些问题不会导致问题和问题的终结,您将花费越来越多的时间来尝试纠正

KeyListener关于文本组件...

在文本组件上放一个KeyListener从来没有一个真正好的理由。如果您想知道该字段何时更新,请使用DocumentListener代替;如果要修改/过滤用户输入字段的内容,请使用DocumentFilter;如果您想知道用户何时按下Enter键,请使用ActionListener

您当前的方法也确实是不健康的,每次释放密钥时尝试执行一个新请求都可能导致您的程序在发出请求时冻结或卡死,它还会执行不必​​要的请求。

取而代之的是,结合使用DocumentListener来检测对字段的更改,并结合使用javax.swing.Timer在更新之间注入一小段延迟,每当通知DocumentListener更改时重新启动计时器。一旦计时器实际触发,就应该执行请求。

组合框更新...

似乎您已经复制并粘贴了代码,因为在cboxLibrarieItemStateChangedcbEdituraItemStateChangedcboxCategorieItemStateChanged方法中,您正在使用cboxAutor中的值...

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


您需要为要搜索的字段使用正确的组合框...

资源管理

您没有很好地管理资源,使连接和其他数据库资源保持打开状态,这可能会随着时间的推移而降低性能。

从Java 7开始,它变得非常易于管理...

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);
}


有关更多详细信息,请参见The try-with-resources Statement

09-10 07:04
查看更多