简体   繁体   English

使用JComboBox而不是JButton填充JTable

[英]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. 我只是Java的初学者,如果您能帮助我,我会很高兴,我这里有一个JTable,它使用JButton填充了数据库中的数据。 I have 3 tables named students , teachers , & directors . 我有3张桌子,分别是学生老师导演 Everything is working fine in viewing those fields in the JTable using the 3 JButtons(one for each table). 使用3个JButton(每个表一个)查看JTable中的那些字段,一切都工作正常。 But everytime I clicked to another JButton, the JTable is not cleared but instead adding the data to the existing information on the JTable. 但是每次我单击另一个JButton时,都不会清除JTable,而是将数据添加到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. 现在,我要做的是将3个JButton替换为JComboBox,其中要选择的选项是表名称,并在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, 只需添加JComboBox而不是像这样的JButton,

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

Add Listener class to combobox like this, 像这样将Listener类添加到组合框,

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. 您需要做的就是为您的JCombobox添加一个ActionListener。 In the actionListener, change the data in the table based on the value returned by the getSelectedItem(). 在actionListener中,根据getSelectedItem()返回的值更改表中的数据。

Try writing it and post your code if you need more help 如果需要更多帮助,请尝试编写并发布代码

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

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