0

I would like to populate a JTable from my database when a user presses a button. At the moment I get no errors, I have established that a DefaultTableModel is being returned to the Action Event of the button and that it contains data. I just can't get the JTable to show the data. I think this is related to where I am declaring the JTable and the GroupLayout addComponent function but I can't figure it out.

Here is the code. I have tried to include the GroupLayout because I am suspicious of it- I've stripped it down as much as possible for the question. I assure this this isn't a code dump:

package Console;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTabbedPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JEditorPane;
import javax.swing.JTable;

public class Console {

    String myquery="";

    private JFrame frame;
    private JTextField textField;
     JTable table_ResQues;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Console window = new Console();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Console() {
        initialize();
    }


    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 950, 800);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
        groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, 838, Short.MAX_VALUE)
                    .addContainerGap())
        );
        groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, 872, Short.MAX_VALUE)
                    .addContainerGap())
        );

        JPanel panel_Question = new JPanel();
        tabbedPane.addTab("Question", null, panel_Question, null);
        JTextArea textAreaQuery = new JTextArea();
        JButton btnNewButton = new JButton("Execute");
        btnNewButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e )
            {

                //Execute when button is pressed
                String connectDB = "jdbc:ucanaccess:///Users/sebastianzeki/Documents/PhysJava/Physiology.mdb;";
                System.out.println("Connection To Database Made");
                Connection conn = null;

                    try {
                        conn = DriverManager.getConnection(connectDB);
                    } catch (SQLException e1) {
                    e1.printStackTrace();
                    }
                    Statement st = null;
                    try {
                        st = conn.createStatement();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                     myquery=textAreaQuery.getText();

                    String stg2 = "Select "+myquery;
                    System.out.println(stg2);
                                        try {
                        ResultSet rs = st.executeQuery(stg2);                           
                        buildTableModel(rs).fireTableDataChanged();
                        table_ResQues.setModel(buildTableModel(rs));

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


        JButton btnExportToCsv = new JButton("Export to CSV");


        GroupLayout gl_panel_Question = new GroupLayout(panel_Question);
        gl_panel_Question.setHorizontalGroup(
            gl_panel_Question.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel_Question.createSequentialGroup()
                    .addGap(41)
                    .addGroup(gl_panel_Question.createParallelGroup(Alignment.LEADING)
                        .addComponent(btnExportToCsv)
                        .addGroup(gl_panel_Question.createSequentialGroup()
                            .addGroup(gl_panel_Question.createParallelGroup(Alignment.LEADING)
                                .addGroup(gl_panel_Question.createSequentialGroup()
                                    .addComponent(textAreaQuery, GroupLayout.PREFERRED_SIZE, 346, GroupLayout.PREFERRED_SIZE)
                                    .addGap(18)
                                    .addGroup(gl_panel_Question.createParallelGroup(Alignment.LEADING)
                                        .addComponent(btnNewButton)))
                                .addComponent(table_ResQues, GroupLayout.PREFERRED_SIZE, 349, GroupLayout.PREFERRED_SIZE))
                            .addGap(18)
                            .addGroup(gl_panel_Question.createParallelGroup(Alignment.TRAILING)
                                .addGroup(gl_panel_Question.createParallelGroup(Alignment.LEADING)
                                    ))
                            .addGap(18)
                            .addGroup(gl_panel_Question.createParallelGroup(Alignment.LEADING))))
                    .addContainerGap(147, Short.MAX_VALUE))
        );
        gl_panel_Question.setVerticalGroup(
            gl_panel_Question.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel_Question.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(gl_panel_Question.createParallelGroup(Alignment.LEADING)
                        .addComponent(textAreaQuery, GroupLayout.PREFERRED_SIZE, 66, GroupLayout.PREFERRED_SIZE)
                        .addGroup(gl_panel_Question.createSequentialGroup()
                            .addComponent(btnNewButton)
                            .addGap(12)
                            .addComponent(btnPostbox)))
                    .addGroup(gl_panel_Question.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel_Question.createSequentialGroup()
                            .addGap(58)
                            .addGroup(gl_panel_Question.createParallelGroup(Alignment.TRAILING, false)
                                .addGroup(gl_panel_Question.createSequentialGroup()
                                    .addGroup(gl_panel_Question.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(button)
                                        .addComponent(btnNewButton_8))
                                    )
                                .addGroup(gl_panel_Question.createSequentialGroup()
                                    )))
                        .addGroup(gl_panel_Question.createSequentialGroup()
                            .addGap(18)
                            .addComponent(table_ResQues, GroupLayout.PREFERRED_SIZE, 190, GroupLayout.PREFERRED_SIZE)))
                    .addGap(28)
                    .addComponent(btnExportToCsv)
                    .addContainerGap(226, Short.MAX_VALUE))
        );
        panel_Question.setLayout(gl_panel_Question);

    }

and the code to populate the model

public static DefaultTableModel buildTableModel(ResultSet rs)
        throws SQLException {

    ResultSetMetaData metaData = rs.getMetaData();
    // names of columns
    Vector<String> columnNames = new Vector<String>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
        System.out.println(metaData.getColumnName(column));
    }

    // data of the table
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (rs.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
    }

    return new DefaultTableModel(data, columnNames);
}
Sebastian Zeki
  • 6,690
  • 11
  • 60
  • 125
  • In this [complete example](http://stackoverflow.com/a/34742409/230513), the table is added to the frame's default `BorderLayout.CENTER`. – trashgod Jun 02 '16 at 11:59
  • 1
    See also this [previous question](http://stackoverflow.com/q/37582796/230513) on the same topic. – trashgod Jun 02 '16 at 12:01
  • I've added the table to the frame but still get the same result. – Sebastian Zeki Jun 02 '16 at 12:29
  • `I've stripped it down as much as possible...` - no you haven't. You have already been told the SQL is irrelevant to the question and given code showing how to exclude this code from the SSCCE. You have also been told a table should be displayed in a JScrollPane. – camickr Jun 02 '16 at 15:36
  • 1
    Instead use nested panels with different layout managers to achieve your desired layout. So what you do is use the default BorderLayout of the frame as the starting point. Then you create a JPanel with a text field and a JButton and add this panel to the BorderLayout.PAGE_START. Then you create a JScrollPane with an empty JTable and add this to the BorderLayout.CENTER. Then in the ActionListener you use the table.setModel() method to update the data. – camickr Jun 02 '16 at 15:41
  • OK yes I will do that. I have it working now. As you say it was a question of just adding it to the JScrollPane – Sebastian Zeki Jun 02 '16 at 15:58

0 Answers0