从数据库更新查询结果的JPanel

问题描述

运行查询,并将每一行放入一个JPanel,并添加显示中供用户查看

我建议您使用a JTable显示数据库中的数据。A JTable被设计为以行/列格式显示数据。

阅读Swing教程中有关如何使用表的部分,获取更多信息和示例。

我希望用户能够根据它们提供的值(通过JTextField)过滤这些结果,并且希望显示的记录随着JTextField值的更改而更新。

A JTable支持动态过滤表中显示的数据。上面的教程中有一节介绍Sorting and Filtering了如何在将文本输入到文本字段中时进行过滤。过滤表比重做SQL查询更有效。

将数据添加到表很简单。无需为每列数据创建一个面板,您可以向TableModel添加新的数据行:

    String sql = "Select * from ???";
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery( sql );
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();

    //  Get column names

    for (int i = 1; i <= columns; i++)
    {
        columnNames.addElement( md.getColumnName(i) );
    }

    //  Get row data

    while (rs.next())
    {
        Vector<Object> row = new Vector<Object>(columns);

        for (int i = 1; i <= columns; i++)
        {
            row.addElement( rs.getobject(i) );
        }

        data.addElement( row );
    }

    //  Create table with database data

    DefaultTableModel model = new DefaultTableModel(data, columnNames)
    {
        @Override
        public Class getColumnClass(int column)
        {
            for (int row = 0; row < getRowCount(); row++)
            {
                Object o = getValueAt(row, column);

                if (o != null)
                {
                    return o.getClass();
                }
            }

            return Object.class;
        }
    };

    JTable table = new JTable( model );
    JScrollPane scrollPane = new JScrollPane( table );

解决方法

当用户最初单击按钮时,将运行查询,并将每一行放入JPanel中并添加到显示中,以供用户查看。哪个工作正常。

我的问题是,我希望用户能够根据它们提供的值(通过JTextField)过滤这些结果,并且我希望显示的记录随着JTextField值的更改而更新。每次更改JTextField时都会形成并执行我的查询,但是我找不到更新显示记录的方法。

任何帮助,将不胜感激。

该代码花了一些时间进行编辑,以使stackoverflow满意,但是就在这里。希望您能遵循逻辑。这是处理查询的形成和执行的方法,该方法再次有效。问题是显示新结果。

private void processSearch(){

int count = 0;
double width;

remove(allInfo);

allInfo = new JPanel();
allInfo.setLayout(new GridLayout(0,1,5,10));

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
width = screenSize.getWidth();


try {

DatabaseConnetor connect = new      DatabaseConnetor();
Connection conn = connect.connect();
String query = "";
String whereClause = "";

int unEmpty = 0;

String [] searches ={searchNameTxt.getText(),searchMailTxt.getText(),searchContactTxt.getText(),(String) searchGender.getSelectedItem()};

String [][] keys = {{"first_name","middle_name","family_name","surname"},{"email"},{"contact","contact2"},{"gender"}};

for(int i=0; i < searches.length; i++){                   
if(!searches[i].trim().isEmpty()){
unEmpty++;
}

for(int i=0; i < searches.length; i++){

int counter = 0;

if(!searches[i].trim().isEmpty()){                  
whereClause += " AND ";

int len = keys[i].length;

if(len == 1){
whereClause += " ("+keys[i][0]+" LIKE '%"+searches[i]+"%') ";
}else if(len > 1){

whereClause += " ( ";

while(counter < len){

if(counter == len-1)
whereClause += keys[i][counter]+" LIKE '%"+searches[i]+"%'";

else
whereClause += keys[i][counter]+" LIKE '%"+searches[i]+"%' OR ";

counter++;
}

whereClause += " ) ";
}
}
}

query = "SELECT photo,first_name,middle_name,family_name,surname,gender,email,contact,contact2 FROM user WHERE rights = 2" + whereClause;

PreparedStatement preparedStatement = conn.prepareStatement(query);

String gen = "",middle = "",family = "",cont = "",phot = "";

ResultSet result = preparedStatement.executeQuery();

while(result.next()){

JPanel data = new JPanel();

data.setPreferredSize(new Dimension((int)(width*0.75),50));

data.setLayout(new GridLayout(1,10));


if(result.getString(1) == "NULL")
phot = "";

data.add(new JLabel(phot)); //Photo

data.add(new JLabel(result.getString(2))); //First Name

if(result.getString(3) == "NULL")
middle = "";

data.add(new JLabel(middle)); //Middle Name

if(result.getString(4) == "NULL")
family = "";

data.add(new JLabel(family)); //Family Name

data.add(new JLabel(result.getString(5))); //Surname

if(result.getString(6).equals("M"))
gen = "Male";
else
gen = "Female";

data.add(new JLabel(gen)); //Gender

data.add(new JLabel(result.getString(7))); //E-Mail

data.add(new JLabel(result.getString(8))); //Contact1

if(result.getString(9) == "NULL")
cont = "";

data.add(new JLabel(cont)); //Contact 2

allInfo.add(data);
}

add(allInfo);

connect.disconnect(conn);
connect = null;
conn = null;

} catch (SQLException e1) {
e1.printStackTrace();
}
}
}