简体   繁体   中英

Populate the JTable using JComboBox instead of a JButton

I am just a beginner in Java and I would be glad if you could help me, I have here a JTable which is populated using JButton with data from the database. I have 3 tables named students , teachers , & directors . Everything is working fine in viewing those fields in the JTable using the 3 JButtons(one for each table). But everytime I clicked to another JButton, the JTable is not cleared but instead adding the data to the existing information on the JTable.

Now, what I want to do is to replace the 3 JButtons into a JComboBox wherein the options to select are the table names and displaying their contents in the JTable. I really don't have any idea on how to do this. I hope you can help me with this and would really appreciate any inputs.

Thanks

Below are the codes I used. I also included some captions.

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

public class tests extends javax.swing.JFrame {

/**
 * Creates new form tests
 */
public tests() {
    initComponents();
}

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

    jScrollPane1 = new javax.swing.JScrollPane();
    dataTable = new javax.swing.JTable();
    students = new javax.swing.JButton();
    teachers = new javax.swing.JButton();
    directors = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

        },
        new String [] {
            "ID", "Name", "Surname", "Age"
        }
    ));
    jScrollPane1.setViewportView(dataTable);

    students.setText("Students");
    students.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            studentsActionPerformed(evt);
        }
    });

    teachers.setText("Teachers");
    teachers.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            teachersActionPerformed(evt);
        }
    });

    directors.setText("Directors");
    directors.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            directorsActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(students)
            .addGap(57, 57, 57)
            .addComponent(teachers)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 66, Short.MAX_VALUE)
            .addComponent(directors)
            .addGap(40, 40, 40))
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(students)
                .addComponent(teachers)
                .addComponent(directors))
            .addGap(18, 18, 18)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE))
    );

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

private void studentsActionPerformed(java.awt.event.ActionEvent evt) {
    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();
    }
}

private void teachersActionPerformed(java.awt.event.ActionEvent evt) {
    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();
    }
}

private void directorsActionPerformed(java.awt.event.ActionEvent evt) {
    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();
    }
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the
     * default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(tests.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(tests.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(tests.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(tests.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new tests().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JTable dataTable;
private javax.swing.JButton directors;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton students;
private javax.swing.JButton teachers;
// End of variables declaration
}

See the caption here.

Thanks in advance.

Just add JComboBox instead of JButtons like this,

String[] items = {"students", "teachers", "directors"};
JComboBox cb = new JComboBox(items);
cb.setEditable(true);

Add Listener class to combobox like this,

ActionListener actionListener = new ActionListener() {
  public void actionPerformed(ActionEvent actionEvent) {
    //System.out.println("Selected: " + cb.getSelectedItem());
     if(cb.getSelectedItem() == "student"){

       //Perform the action for student

     } 

      //Repeat this for all items

  }
};
cb.addActionListener(actionListener);

This will do what you are expecting....

All you need to do is add an ActionListener for your JCombobox. In the actionListener, change the data in the table based on the value returned by the getSelectedItem().

Try writing it and post your code if you need more help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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