1
votes

I'm trying to put a JTable within a JPanel but only appears if I use the JOptionPane method. I also tried adding a button to the table but that doesn't appear either. I just want the JTable to open and the user to be able to select a row which I can then put in a String

I have JFrame but which the panel is added too but that doesn't work either.

Thank You.

public static void main(String[] args) throws Exception {
    // The Connection is obtained

    ResultSet rs = stmt.executeQuery("select * from product_info");

    JPanel panel = new JPanel();
                panel.setLayout(new BorderLayout());

                JTable table = new JTable(buildTableModel(rs));
                System.out.println(table.getSelectedRow());
                JButton choose = new JButton("Choose");

                panel.add(choose, BorderLayout.SOUTH); // e.g. for the button
                panel.add(new JScrollPane(table), BorderLayout.CENTER);

                JOptionPane.showMessageDialog(null, new JScrollPane(table));

}

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

    // 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);
}
2
re "I have JFrame but which the panel is added too but that doesn't work either." -- please show the code where you do this. "but that doesn't work either" tells us nothing of use. Instead show us.Hovercraft Full Of Eels

2 Answers

2
votes

Your JOptionPane contains only the table (wrapped in a JScrollPane) because you told it to:

JOptionPane.showMessageDialog(null, new JScrollPane(table));

If you want it to contain the panel, use:

JOptionPane.showMessageDialog(null, panel);
1
votes

If you don't use a JOptionPane, what top level window do you have that will display anything? A JPanel or a JTable or a JScrollPane cannot display themselves but rather need to be in a top level window to display, such as a JFrame or JDialog or (here) a JOptionPane.

Solution: put your JPanel into a JFrame, pack the JFrame and display it. Edit: or display the JPanel in the JOptionPane as immibis recommends, 1+ to his answer).