登录时从数据库填充JTable

时间:2018-09-27 23:22:44

标签: java swing jdbc

我正在使用JDBC从Oracle数据库连接中填充JTable。当前正在运行,但是我正在尝试对破坏它的代码进行修改。

当前,它在创建JTable时通过查询数据库来填充JTable。

我正在尝试将此功能移至ActionListener。基本上,我想创建一个空表,然后当用户按下JButton时,它应该运行sql查询并填充并重新绘制该表。我已经尝试了所有我能想到的一切,但我不禁认为这是一个基本的尝试,但是我的逻辑使我失望了。

当前实施:

private void makeTable() {
    Vector columnNames = new Vector();
    Vector data = new Vector();
    String userName = "aUsername";
    String password = "aPassword";
    try {
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        Connection connection = DriverManager.getConnection("redactedDatabaseConnection", userName, password);
        String sql = "select upper(choreName) as Chore, dueDate as due, completedDate as completed, fname as completedby from chore inner join choreCompletion on chore.choreid = chorecompletion.choreid inner join users on users.userID = choreCompletion.completedby";  

        Statement statement = connection.prepareStatement(sql);
        ResultSet rset = statement.executeQuery(sql);
        ResultSetMetaData metaData = rset.getMetaData();
        int columns = metaData.getColumnCount();
        for (int i = 1; i <= columns; i++) {
            columnNames.addElement(metaData.getColumnName(i));
        }
        while (rset.next()) {
            Vector row = new Vector(columns);
            for (int i = 1; i <= columns; i++) {
                row.addElement(rset.getObject(i));
            }
            data.addElement(row);
        }
        rset.close();
        statement.close();
        connection.close();
    } catch (SQLException ex) {ex.printStackTrace();}
    JTable choresTable = new JTable(data, columnNames);
    TableColumn column;
    for (int i = 0; i<choresTable.getColumnCount(); i++) {
        column = choresTable.getColumnModel().getColumn(i);
        column.setMaxWidth(250);
    }
    JScrollPane scrollPane = new JScrollPane(choresTable);
    scrollPane.getViewport().setBackground(new Color(144, 167, 204));
}

编辑: 当前尝试实施

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

@SuppressWarnings("unchecked")
public class FillTable extends JFrame
{
private Vector columnNames, data, row;
private Connection connection;
private final String dbUsername = "aUsername";
private final String dbPassword = "aPassword";

private JTable groceryTable;
private TableColumn column;
private JScrollPane pane;
private JPanel panel;

public FillTable()
{
    try {
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    } catch(Exception e){
        e.printStackTrace();
    }
    createComponents();
    setSize(800,800);
    setTitle("A filled Table");
}

public static void main(String[] args)
{
    JFrame frame = new FillTable();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setUndecorated(false);
    frame.setLocationRelativeTo(null);
    frame.setResizable(true);
    frame.setVisible(true);
}

class ButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        try {
            connection = DriverManager.getConnection("redactedServerInfo", dbUsername, dbPassword);
            String sql = "select upper(name) as Grocery, fname as ordered_by, dateordered as date_ordered from groceries inner join grocerylist on groceries.groceryid=grocerylist.groceryid inner join users on grocerylist.orderedby= users.userid";  
            Statement statement = connection.prepareStatement(sql);
            ResultSet rset = statement.executeQuery(sql);
            ResultSetMetaData metaData = rset.getMetaData();
            int columns = metaData.getColumnCount();
            for (int i=1; i<= columns; i++) {
                columnNames.addElement(metaData.getColumnName(i));
            }
            while (rset.next()) {
                row = new Vector(columns);
                for(int i=1;i<=columns;i++) {
                    row.addElement(rset.getObject(i));
                }
                data.addElement(row);
            }
            rset.close();
            statement.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        for(int i=0;i<groceryTable.getColumnCount(); i++) {
            column = groceryTable.getColumnModel().getColumn(i);
            column.setMaxWidth(250);
        }
        pane.repaint();
        pane.revalidate();
        groceryTable.repaint();
        groceryTable.revalidate();
        panel.repaint();
        panel.revalidate();
        repaint();
        revalidate();
    }
}

private void createComponents()
{
    JButton button = new JButton("Press me");

    ActionListener buttonListener = new ButtonListener();
    button.addActionListener(buttonListener);

    columnNames = new Vector();
    data = new Vector();
    row = new Vector();

    groceryTable = new JTable(data, columnNames);

    pane = new JScrollPane(groceryTable);

    panel = new JPanel();
    panel.add(button);
    panel.add(pane);
    add(panel);
}   

}

4 个答案:

答案 0 :(得分:1)

使用0行作为字段创建表。

之后

connection.close();

choresTable.setModel(new DefaultTableModel(data, columnNames));

因此具有模型的瞬时表创建代码因此可以移至常规创建代码。

设置model足以重绘。

答案 1 :(得分:1)

基本上,您想要创建并显示一个空的JTableActionListener应该更新表模型:

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

//based on 
//https://docs.oracle.com/javase/tutorial/uiswing/examples/components/SimpleTableDemoProject/src/components/SimpleTableDemo.java
public class SimpleTableDemo extends JPanel {

    private JTable table;
    private JButton populate;

    public SimpleTableDemo() {

        makeTable();
        populate = new JButton("Populate");
        populate.addActionListener(e -> populateTable());
        add(populate, BorderLayout.SOUTH);
    }

    private void makeTable() {
        String[] columnNames = {"click button to populate table"};
        Object[][] data = new  Object[][] {};
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }
    private void populateTable() {

        populate.setEnabled(false);
        DefaultTableModel model =  ((DefaultTableModel) table.getModel());
        String[] columnNames = {"First Name", "Last Name"};
        Object[][] data = {
                {"Kathy", "Smith"},
                {"John", "Doe"},
                {"Sue", "Black"},
                {"Jane", "White"},
                {"Joe", "Brown"}
        };
        model.setDataVector(data, columnNames);
    }

    private static void createAndShowGUI() {

        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        SimpleTableDemo newContentPane = new SimpleTableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

答案 2 :(得分:0)

希望您熟悉Task,TableView和ObservableList…。

您可以在Task类中的控制器中使用FXCollections.observableList(可以在控制器中创建本地类并扩展Task)和TableView

基本上使用一种方法,该方法将提取sql查询结果并将这些结果转换为list,而不是返回要在FXCollection.observableList的形式参数中填充的项目的列表。

将TableView列与要执行的“任务”绑定在一起,即,在这种情况下,您可能希望将每个列与从列表中获得的不同字段绑定在一起,现在将按钮与调用Thread的方法绑定在一起(task).start方法,一切应该正常。

答案 3 :(得分:0)

经过大量的研究和许多失败的尝试,我最终解决了这个问题。解决方案的关键是引入了一个帮助程序方法,该方法返回一个表模型以将更新触发到表。

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

@SuppressWarnings("unchecked")
public class FillTable extends JFrame
{
    private Vector columnNames, data, row;
    private Connection connection;
    private final String dbUsername = "aUsername";
    private final String dbPassword = "aPass";

    private JTable groceryTable;
    private TableColumn column;
    private JScrollPane pane;
    private JPanel panel;

    public FillTable()
    {
        createComponents();
        setSize(800,800);
        setTitle("A filled Table");
    }

    public static void main(String[] args)
    {
        JFrame frame = new FillTable();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(false);
        frame.setLocationRelativeTo(null);
        frame.setResizable(true);
        frame.setVisible(true);
    }

class ButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        try {
            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
            connection = DriverManager.getConnection("redactedDBINFO", dbUsername, dbPassword);
            String sql = "select upper(name) as Grocery, fname as ordered_by, dateordered as date_ordered from groceries inner join grocerylist on groceries.groceryid=grocerylist.groceryid inner join users on grocerylist.orderedby= users.userid";  
            Statement statement = connection.prepareStatement(sql);
            ResultSet rset = statement.executeQuery(sql);            
            groceryTable.setModel(updateModel(rset));
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

public DefaultTableModel updateModel(ResultSet rset) throws SQLException
{

    ResultSetMetaData metaData = rset.getMetaData();

    Vector<String> columnNames = new Vector<String>();

    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
    }

    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (rset.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(rset.getObject(columnIndex));
        }
        data.add(vector);
    }
    return new DefaultTableModel(data, columnNames);
}

private void createComponents()
{
    JButton button = new JButton("Press me");
    ActionListener buttonListener = new ButtonListener();
    button.addActionListener(buttonListener);

    groceryTable = new JTable();

    pane = new JScrollPane(groceryTable);

    panel = new JPanel();
    panel.add(button);
    panel.add(pane);
    add(panel);
}   
}