JTable行选择和数据检索

时间:2013-10-03 14:24:58

标签: java swing jtable

这是我第一次创建一个程序,该程序将连接到数据库以获取数据并将其放在JTable中。

现在问题是我想从上表中选择一行并在指定的JTextFields中显示结果。

我尝试了很多谷歌提供的搜索结果,但我仍然无法弄清楚如何做到这一点。

以下是该计划的完整源代码。

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();   

}
} 

我想知道如何做到这一点。任何回复/答案将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:2)

阅读How to Write a List Selection Listener上的Swing教程中的部分。

当选择更改时,您将获得当前选定的行。然后,您可以通过对每个文本字段使用table.getValueAt(...)方法在文本字段中显示数据。

另外,不要使用setBounds()。 Swing旨在与布局管理器一起使用。本教程还有一个关于布局管理器的部分,您可以阅读它以获取更多信息。

答案 1 :(得分:1)

我没有看到你添加任何监听器来监听行选择更改。不确定,你看过google搜索的内容。示例代码(当取消选择行时,可以针对其他值进行增强/清除值)

    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);


        }
    });