简体   繁体   English

使用JComboBox从数据库检索数据清除JTable

[英]Clear JTable with data retrieve from database using JComboBox

just beginning my hands on Java and badly needs your help. 刚开始接触Java时,急需您的帮助。 I have a JComboBox that retrieves data from a database and displaying it in a JTable. 我有一个JComboBox,它从数据库检索数据并将其显示在JTable中。 My problem is when I select to Students , it displays the data about Students and when selecting to another option just like Teacher , it also display data about the Teacher but it is appended on the data displayed by Students. 我的问题是,当我选择“ 学生”时 ,它会显示有关“学生”的数据,而当选择“ 教师 ”之类的另一个选项时,它还会显示有关“教师”的数据,但它会附加在“学生”显示的数据上。 I wonder how can I display the data of Students only and same with others. 我想知道如何显示学生的数据并与他人相同。

Below is the code I used. 下面是我使用的代码。 Maybe I'm missing something. 也许我想念一些东西。

import javax.swing.*;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;


public class VisibilityTool extends javax.swing.JFrame {

public VisibilityTool() {
    initComponents();
}


//Generate
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    eMail = new javax.swing.JLabel();
    comBox = new javax.swing.JComboBox();
    emailText = new javax.swing.JTextField();
    buttonGenerate = new javax.swing.JButton();
    progressBar = new javax.swing.JProgressBar();
    selectEnvironment = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    dataTable = new javax.swing.JTable();
    jMenuBar1 = new javax.swing.JMenuBar();
    file = new javax.swing.JMenu();
    exit = new javax.swing.JMenuItem();
    help = new javax.swing.JMenu();
    about = new javax.swing.JMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("[Trax] Data Visibility Tool");
    setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    setFocusCycleRoot(false);
    setForeground(java.awt.Color.black);

    eMail.setBackground(new java.awt.Color(51, 51, 51));
    eMail.setFont(new java.awt.Font("Lucida Bright", 1, 12)); // NOI18N
    eMail.setText("E - mail address :");

    comBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select . . .", "Students", "Teachers", "Directors" }));
    comBox.setToolTipText("'Choose the database to query'");
    comBox.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            comBoxActionPerformed(evt);
        }
    });

    emailText.setToolTipText("'Put you e-mail address here'");
    emailText.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            emailTextActionPerformed(evt);
        }
    });

    buttonGenerate.setText("GENERATE");
    buttonGenerate.setToolTipText("'GENERATE'");
    buttonGenerate.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonGenerateActionPerformed(evt);
        }
    });

    selectEnvironment.setBackground(new java.awt.Color(51, 51, 51));
    selectEnvironment.setFont(new java.awt.Font("Lucida Bright", 1, 12)); // NOI18N
    selectEnvironment.setText("Select Environment :");

    dataTable.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {

        },
        new String [] {
            "ID", "Name", "Surname", "Age"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    dataTable.getTableHeader().setReorderingAllowed(false);
    jScrollPane1.setViewportView(dataTable);
    dataTable.getColumnModel().getColumn(0).setResizable(false);
    dataTable.getColumnModel().getColumn(1).setResizable(false);
    dataTable.getColumnModel().getColumn(2).setResizable(false);
    dataTable.getColumnModel().getColumn(3).setResizable(false);

    file.setText("File");
    file.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            fileActionPerformed(evt);
        }
    });

    exit.setText("Exit");
    exit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            exitActionPerformed(evt);
        }
    });
    file.add(exit);

    jMenuBar1.add(file);

    help.setText("Help");
    help.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            helpActionPerformed(evt);
        }
    });

    about.setText("About");
    about.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            aboutActionPerformed(evt);
        }
    });
    help.add(about);

    jMenuBar1.add(help);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 483, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(buttonGenerate)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(eMail, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(43, 43, 43)
                                    .addComponent(emailText, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(selectEnvironment, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(comBox, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(selectEnvironment, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(comBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(27, 27, 27)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(eMail, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(emailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(30, 30, 30)
            .addComponent(buttonGenerate)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(19, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void comBoxActionPerformed(java.awt.event.ActionEvent evt) {                                         
    if (comBox.getSelectedItem() == "Select . . .") {


    } else if (comBox.getSelectedItem() == "Students") {
    DefaultTableModel model = (DefaultTableModel) dataTable.getModel();  
    String sql = "select * from students";
    try {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(tests.class.getName()).log(Level.SEVERE, null, ex);
        }
        Connection connect = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/datavisibility","root","");
        Statement statmnt = connect.createStatement();
        ResultSet rslt = statmnt.executeQuery(sql);
        while(rslt.next()){
            String id = rslt.getString("ID");
            String name = rslt.getString("Name");
            String surname = rslt.getString("Surname");
            String age = rslt.getString("Age");
            model.addRow(new Object[]{id,name,surname,age});

        }
    } catch(SQLException e){
        e.printStackTrace();
    }
    } else if (comBox.getSelectedItem() == "Teachers"){
    DefaultTableModel model = (DefaultTableModel) dataTable.getModel();
    String sql = "select * from teachers";
    try {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(tests.class.getName()).log(Level.SEVERE, null, ex);
        }
        Connection connect = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/datavisibility","root","");
        Statement statmnt = connect.createStatement();
        ResultSet rslt = statmnt.executeQuery(sql);
        while(rslt.next()){
            String id = rslt.getString("ID");
            String name = rslt.getString("Name");
            String surname = rslt.getString("Surname");
            String age = rslt.getString("Age");
            model.addRow(new Object[]{id,name,surname,age});

        }
    } catch(SQLException e){
        e.printStackTrace();
    }
    } else if (comBox.getSelectedItem() == "Directors") {
    DefaultTableModel model = (DefaultTableModel) dataTable.getModel();
    String sql = "select * from directors";
    try {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(tests.class.getName()).log(Level.SEVERE, null, ex);
        }
        Connection connect = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/datavisibility","root","");
        Statement statmnt = connect.createStatement();
        ResultSet rslt = statmnt.executeQuery(sql);
        while(rslt.next()){
            String id = rslt.getString("ID");
            String name = rslt.getString("Name");
            String surname = rslt.getString("Surname");
            String age = rslt.getString("Age");
            model.addRow(new Object[]{id,name,surname,age});

        }
    } catch(SQLException e){
        e.printStackTrace();
    }
    }
}        

Thanks a lot for your help. 非常感谢你的帮助。

1) define TableModel only once time (meaning code lines) 1)仅定义一次TableModel (含义代码行)

DefaultTableModel model = (DefaultTableModel) dataTable.getModel();

2) remove all row from TableModel with reversal way 2)以逆向方式从TableModel删除所有行

if (model.getRowCount() > 0) {
    for (int i = model.getRowCount() - 1; i > 0; i--) {
        model.removeRow(i);
    }
}

3) then add new rows from ResultSet 3)然后从ResultSet添加新行

4) this code have got issue with Concurency in Swing and all GUI is un_responsible untill ResultSet ended, on Exceptions from ResultSet only Mouse hover_over the JTable's rows refreshing GUI, better would be invoke ResultSet from SwingWorker or Runnable#Thread 4)这段代码在Swing中的Concurency上出现问题,并且所有的GUI都不负责,直到ResultSet结束,在ResultSet Exceptions ,只有将Mouse hover_overJTable's行刷新GUI上,最好从SwingWorkerRunnable#Thread调用ResultSet

5) please write code by your hands, because for 90pct of potential answerers (inc. me) is not possible to runs generated code from some IDE and without definitions for local variables 5)请亲手编写代码,因为对于90pct的潜在答题者(包括我),无法从某些IDE运行生成的代码,并且没有局部变量的定义

Before adding remove all the old values (rows?) from the model. 在添加之前,请从模型中删除所有旧值(行?)。 Use public void removeRow(int row) method of model. 使用模型的public void removeRow(int row)方法。

Some day before I wrote a TableModel, here it is: 在我写TableModel的前一天,它是:

public class MovieSearchResultTableModel extends AbstractTableModel {

    private static final long serialVersionUID = 46L;

    private List<MovieSearchModel> movieSearchModels;
    private ComponentConstant.ColumnName[] columns = ComponentConstant.Column.MOVIE_SEARCH_RESULT_TABLE;

    public int getRowCount() {
        return movieSearchModels.size();
    }

    public int getColumnCount() {
        return columns.length;
    }

    @Override
    public String getColumnName(int columnIndex) {
        return columns[columnIndex].getName();
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return columns[columnIndex].getClass();
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        Object returnValue = new Object();
        switch(columnIndex) {
            case 0: 
                returnValue = movieSearchModels.get(rowIndex).getName();
                break;
            case 1: 
                returnValue = movieSearchModels.get(rowIndex).getReleased();
                break;
            case 2: 
                returnValue = movieSearchModels.get(rowIndex).getLanguage();
                break;
            case 3: 
                returnValue = movieSearchModels.get(rowIndex).getRating();
                break;
            case 4: 
                returnValue = movieSearchModels.get(rowIndex).getCertification();
                break;
            case 5: 
                returnValue = movieSearchModels.get(rowIndex).getImdb_id();
                break;
        }       
        return returnValue;
    }

    public List<MovieSearchModel> getMovieSearchModels() {
        return movieSearchModels;
    }

    public void setMovieSearchModels(List<MovieSearchModel> movieSearchModels) {
        this.movieSearchModels = movieSearchModels;
    }
}

It is complicated. 这很复杂。 But the basic logic is, it has a list of object movieSearchModels . 但基本逻辑是,它具有对象movieSearchModels的列表。 Its of type MovieSearchModel and the method getValueAt() populates the table. 其类型为MovieSearchModel ,方法为getValueAt()填充表。 When I need to change the TableModel, I extract the model from table and set new value to movieSearchModels , then fire fireTableDataChanged with the help of TableModel. 当我需要更改TableModel时,我从表中提取模型并将新值设置为movieSearchModels ,然后在TableModel的帮助下触发fireTableDataChanged Like: 喜欢:

List<MovieSearchModel> movieSearchModels = ModelUtils.getMovieSearchModels(movieSearchResults);
MovieSearchResultTableModel movieSearchResultTableModel = (MovieSearchResultTableModel) ModelFactory.getMovieSearchResultTableModel();
movieSearchResultTableModel.setMovieSearchModels(movieSearchModels);
movieSearchResultTableModel.fireTableDataChanged();

If you have any doubts you can ask. 如果您有任何疑问,可以询问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM