Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7599919
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T22:46:46+00:00 2026-05-30T22:46:46+00:00

I am just a beginner in Java and I would be glad if you

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T22:46:48+00:00Added an answer on May 30, 2026 at 10:46 pm

    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….

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Could someone please help me in here, I'm just a beginner who want to
Ok, I am beginner in JAVA. I have just started. I downloaded Java SE
I have two questions - I'm a beginner in Java but have a huge
We're developing a data heavy modular web application stack with java but have little
Forgive my ignorance, but I am a beginner in java that comes from using
i m just a beginner and i m using c++, wxwidget and mysql manually
I have just finished up my first book on Java training and I think
i am just a beginner with gtk. i have created some of the example
I am a beginner to SONAR , i just need a help for a
I am just a beginner in ASP.NET. My question is simple, I wanna add

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.