terrible-coder
terrible-coder

Reputation: 333

JTable row selection and data retrieval

It is my first time creating a program which will connect to a database to fetch the data and place it in a JTable.

Now the problem is I want to select a row from the above table and display the results in the specified JTextFields.

I have tried many search results provided by Google but I can't still figure out how to do it.

Here is the complete source code for the program.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.table.*;

public class MalayaUniversityEnrollment extends JFrame //implements ActionListener
{
JLabel header = new JLabel ("MALAYA UNIVERSITY ENROLLMENT SYSTEM");

JLabel searchHeader = new JLabel ("SEARCH A STUDENT ");
JLabel infoHeader = new JLabel ("STUDENT INFORMATION");

JButton addButton = new JButton ("ENROLL STUDENT");
JButton editButton = new JButton ("EDIT INFO");
JButton deleteButton = new JButton ("DELETE STUDENT");
JButton searchButton = new JButton ("SEARCH IT!");
JButton clearButton = new JButton ("CLEAR ALL FIELDS");

JTextField studentIDField = new JTextField();
JTextField lastNameField = new JTextField();
JTextField firstNameField = new JTextField();
JTextField middleInitialField = new JTextField();
JTextField CYSField = new JTextField();
JTextField tuitionField = new JTextField();
JTextField statusField = new JTextField();
JTextField searchField = new JTextField();

JLabel studentIDLabel = new JLabel ("Student ID Number: ");
JLabel lastNameLabel = new JLabel ("Last Name: ");
JLabel firstNameLabel = new JLabel ("First Name: ");
JLabel middleInitialLabel = new JLabel ("Middle Initial: ");
JLabel CYSLabel = new JLabel ("CYS: ");
JLabel tuitionLabel = new JLabel ("Semestral Tuition: ");
JLabel statusLabel = new JLabel ("Status: ");
private final JTable table = new JTable();
private final JScrollPane scrollPane = new JScrollPane();

String SID ="";
String lastName="";
String firstName="";
String middleInitial="";
String CYS="";
Double semestralTuition=0.00;
String studentStatus="";

String[] headers = {"Student ID", "Last Name", "First Name", "Middle Initial","CYS", "Semestral Tuition", "Status"};

DefaultTableModel model = new DefaultTableModel();

public MalayaUniversityEnrollment()
{
    super ("Malaya University [Enrollment]");

    Container c = getContentPane();
    c.setLayout(null);

    c.add(header);
    header.setBounds(290,20,1000,35);
    header.setFont(new Font("Tahoma", Font.PLAIN, 35));

    c.add(addButton);
    c.add(editButton);
    c.add(deleteButton);
    c.add(searchButton);
    c.add(clearButton);

    c.add(searchHeader);
    c.add(infoHeader);

    c.add(studentIDField);
    c.add(lastNameField);
    c.add(firstNameField);
    c.add(middleInitialField);
    c.add(CYSField);
    c.add(tuitionField);
    c.add(statusField);
    c.add(searchField);

    c.add(studentIDLabel);
    c.add(lastNameLabel);
    c.add(firstNameLabel);
    c.add(middleInitialLabel);
    c.add(CYSLabel);
    c.add(tuitionLabel);
    c.add(statusLabel);

    studentIDLabel.setBounds(50,575,100,30);
    lastNameLabel.setBounds(50,615,100,30);
    firstNameLabel.setBounds(50,660,100,30);
    middleInitialLabel.setBounds(50,700,100,30);

    studentIDField.setBounds(175,575,200,30);
    lastNameField.setBounds(175,615,200,30);
    firstNameField.setBounds(175,660,200,30);
    middleInitialField.setBounds(175,700,200,30);

    CYSLabel.setBounds(450,575,100,30);
    tuitionLabel.setBounds(450,615,100,30);
    statusLabel.setBounds(450,660,100,30);

    CYSField.setBounds(575,575,200,30);
    tuitionField.setBounds(575,615,200,30);
    statusField.setBounds(575,660,200,30);

    infoHeader.setBounds(270,525,500,50);
    infoHeader.setFont(new Font("Tahoma", Font.PLAIN, 30));

    searchField.setBounds(885,638,300,30);
    searchHeader.setBounds(895,575,300,50);
    searchHeader.setFont(new Font("Tahoma", Font.PLAIN, 30));

    searchButton.setBounds(938,688,200,23);

    addButton.setBounds(450,700,146,23);
    editButton.setBounds(630,700,146,23);
    deleteButton.setBounds(450,733,146,23);
    clearButton.setBounds(630,733,146,23);

    studentIDField.setHorizontalAlignment(JTextField.CENTER);
    lastNameField.setHorizontalAlignment(JTextField.CENTER);
    firstNameField.setHorizontalAlignment(JTextField.CENTER);
    middleInitialField.setHorizontalAlignment(JTextField.CENTER);
    CYSField.setHorizontalAlignment(JTextField.CENTER);
    tuitionField.setHorizontalAlignment(JTextField.CENTER);
    statusField.setHorizontalAlignment(JTextField.CENTER);
    searchField.setHorizontalAlignment(JTextField.CENTER);


    scrollPane.setBounds(50, 88, 1190, 412);

    getContentPane().add(scrollPane);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setShowGrid(true);

    model.setColumnIdentifiers(headers);
    table.setModel(model);
    scrollPane.setViewportView(table);

    JTableHeader header = table.getTableHeader();

    header.setDefaultRenderer(new HeaderRenderer(table));

    table.getTableHeader().setReorderingAllowed(false);



    setSize(1300,825);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    for (int y=0; y<7; y++)
    {
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment( JLabel.CENTER );
        table.getColumnModel().getColumn(y).setCellRenderer( centerRenderer );
    }


    RetrieveData();
}

private static class HeaderRenderer implements TableCellRenderer 
    {

        DefaultTableCellRenderer renderer;

        public HeaderRenderer(JTable table) 
        {
            renderer = (DefaultTableCellRenderer)
            table.getTableHeader().getDefaultRenderer();
            renderer.setHorizontalAlignment(JLabel.CENTER);
        }


        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus, int row, int col) 

        {
            return renderer.getTableCellRendererComponent(
            table, value, isSelected, hasFocus, row, col);
        }
}

public void RetrieveData()
{
    try 
    {
        int x=0;
        String query = "Select * FROM `2013-2014 enrollment`";
        DatabaseConfig a = new DatabaseConfig();
        ResultSet rs = a.showR(query);

        while(rs.next())
        {
            SID = rs.getString("Student_ID");
            lastName = rs.getString("Last_Name");
            firstName = rs.getString("First_Name");
            middleInitial = rs.getString("Middle_Initial");
            CYS = rs.getString("CYS");
            semestralTuition = rs.getDouble("Semestral_Tuition");
            studentStatus = rs.getString("Status");

            model.addRow(new Object[]{SID,lastName,firstName,middleInitial,CYS,semestralTuition,studentStatus});


            x++;

            System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) + " " + rs.getString(7));
        }



    } 
    catch (Exception e) 
    {
        JOptionPane.showMessageDialog(null, "There is an error.");
    }
}

public static void main (String[] args)
{
    try 
    {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }

    catch (Exception exe)
    {
        System.out.println("ERROR: Could not Load System UI.");
    }


    new MalayaUniversityEnrollment();   

}
} 

I want to find out exactly how to do it. Any response/answers will be appreciated. Thanks in advance.

Upvotes: 0

Views: 988

Answers (2)

Optional
Optional

Reputation: 4507

I don't see you have added any Listener to listen to row selection change. Not sure, what google search you looked at. Sample code (can be enhanced for other values/clearing of values when row is unselected)

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            int selectedRow = table.getSelectedRow();
           String sid = (String)table.getValueAt(selectedRow, 0);
           studentIDField.setText(sid);


        }
    });

Upvotes: 1

camickr
camickr

Reputation: 324108

Read the section from the Swing tutorial on How to Write a List Selection Listener.

When the selection changes you get the currently selected row. Then you can display data in your text fields by using the table.getValueAt(...) method for each of your text fields.

Also, don't use setBounds(). Swing was designed to be used with Layout Managers. The tutorial also has a section on layout managers that you can read for more information.

Upvotes: 2

Related Questions