0

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();
}
Community
  • 1
  • 1
vagg77
  • 97
  • 2
  • 15
  • `null` layouts == more trouble than they are worth, make use of an appropriate layout manager, wrap the `JTabel` in a `JScrollPane` and let Swing take care of the rest. – MadProgrammer Aug 06 '14 at 08:29

3 Answers3

2

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

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

JTableHeader tableHeader = table.getTableHeader();
frame.getContentPane().add(tableHeader);
Deutro
  • 3,113
  • 4
  • 18
  • 26
  • Ok it compiles but stays the same. I believe my error is somewhere here `DefaultTableModel model = new DefaultTableModel(cols,0);` – vagg77 Aug 06 '14 at 08:24
  • @vagg77 No - your error is with the layout manager! If there is no layout manager you must specify the size of all the components you add to the container, which means you need to set the size of the `JScrollPane`, not the table - or just don't use `null` layouts – MadProgrammer Aug 06 '14 at 08:27
  • As LayoutManager I can recommend you MigLayout. It is very nice and you can write amazing GUIs with readable code. http://miglayout.com – Deutro Aug 06 '14 at 08:49
0

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.

icza
  • 389,944
  • 63
  • 907
  • 827