Karl
Karl

Reputation: 13

Clear JTable with data retrieve from database using JComboBox

just beginning my hands on Java and badly needs your help. I have a JComboBox that retrieves data from a database and displaying it in a 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.

Upvotes: 1

Views: 1703

Answers (3)

Tapas Bose
Tapas Bose

Reputation: 29806

Some day before I wrote a TableModel, here it is:

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. Its of type MovieSearchModel and the method getValueAt() populates the table. 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. 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.

Upvotes: 0

StanislavL
StanislavL

Reputation: 57381

Before adding remove all the old values (rows?) from the model. Use public void removeRow(int row) method of model.

Upvotes: 3

mKorbel
mKorbel

Reputation: 109815

1) define TableModel only once time (meaning code lines)

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

2) remove all row from TableModel with reversal way

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

3) then add new rows from 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

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

Upvotes: 3

Related Questions