vagg77
vagg77

Reputation: 97

JTable columns wont show up

Im having an issue with JTable columns. I create the JTable but the columns wont show up.And yes, I tried the previously asked question about this issue saying about adding a JScrollPane but putting the ScrollPane inside destroyed completely my Table and the Table wasn't visible.

I tried frame.getContentPane.add(new JScrollPane(table)) from this link (JTable won't show column headers) but didnt have any effect as I said above.

Im not using a layout manager.

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
String[] cols = new String[columnCount];
   for (i=1;i<= columnCount;i++)
     {
        cols[i-1] = md.getColumnName(i);
     }
DefaultTableModel model = new DefaultTableModel(cols,0);
    while (rs.next())
     {
        Object[] row = new Object[columnCount];
          for (i = 1 ; i <= columnCount ; i++)
            {
              row[i-1] = rs.getObject(i);
            }
       model.addRow(row);
     }
JTable table = new JTable(model);
model.fireTableDataChanged();
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(146,59,763,360);
frame.getContentPane().add((table));
model.fireTableDataChanged();
}

Upvotes: 0

Views: 138

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347294

JTable is designed to work with JScrollPane, it will automatically add the TableHeader to the scroll pane, for example

Instead of

frame.getContentPane().add((table));

Try using...

frame.getContentPane().add(new JScrollPane(table));

See How to Use Tables for more details

Tables

Beware, you should avoid using setBounds and instead use an appropriate layout manager, you should also void using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

Updated...

You should never need to call fireTableDataChanged or any other event methods on a model, they are not meant for your use, but for use within the model.

Before adding the table/scroll pane to the content pane, try this...

frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JScrollPane(table));

Let me demonstrate...

With a layout manager...

With layout

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class TableExample {

    public static void main(String[] args) {
        new TableExample();
    }

    public TableExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                int columnCount = 10;
                String[] cols = new String[columnCount];
                for (int i = 1; i <= columnCount; i++) {
                    cols[i - 1] = Integer.toString(i);
                }
                DefaultTableModel model = new DefaultTableModel(cols, 0);
                JTable table = new JTable(model);

                table.setCellSelectionEnabled(true);
                table.setColumnSelectionAllowed(true);
                table.setFillsViewportHeight(true);
                table.setSurrendersFocusOnKeystroke(true);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

Without a layout manager...

withoutwithout

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class TableExample {

    public static void main(String[] args) {
        new TableExample();
    }

    public TableExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                int columnCount = 10;
                String[] cols = new String[columnCount];
                for (int i = 1; i <= columnCount; i++) {
                    cols[i - 1] = Integer.toString(i);
                }
                DefaultTableModel model = new DefaultTableModel(cols, 0);
                JTable table = new JTable(model);

                table.setCellSelectionEnabled(true);
                table.setColumnSelectionAllowed(true);
                table.setFillsViewportHeight(true);
                table.setSurrendersFocusOnKeystroke(true);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(null);
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

The problem isn't with the code you've shown us, the problem is with your choice to do away with one of the core concepts upon which the Swing API is built on...the layout manager

Upvotes: 2

icza
icza

Reputation: 417877

Either you have to wrap your table in a JScrollPane like this:

frame.getContentPane().add(new JScrollPane(table));

Or you have to add the table header separatly:

frame.getContentPane().add(table.getTableHeader, BorderLayout.NORTH);
frame.getContentPane().add(table); // By default this adds to CENTER

This assumes the layout manager of the content pane is the default BorderLayout.

Upvotes: 0

Deutro
Deutro

Reputation: 3323

You can try to get the TableHeader from the Table and add this to the ContentPane:

JTableHeader tableHeader = table.getTableHeader();
frame.getContentPane().add(tableHeader);

Upvotes: 1

Related Questions