Column Headers not shown up in JTable

160 views Asked by At

Though I have read all the relevant answers, I am still stuck on the question of how to display the column headers in a JTable. I tried adding JScrollPane but it did not work. Any help please. Below is given the code:

        frame = new JFrame();

        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new CardLayout(0, 0));

        final JPanel panel = new JPanel();
        final JPanel panel_1 = new JPanel();
        final JTable table = new JTable();
        frame.getContentPane().add(panel, "name_762477085406274");
        panel.setLayout(null);

        JButton btnOk = new JButton("ok");
        btnOk.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                panel.setVisible(false);
                panel_1.setVisible(true);


                final Connection connect; 
                final Statement statement; 
                final ResultSet resultset;

                try
                {
                        Class.forName("com...."); 

                        connect = DriverManager.getConnection("jdbc:mysql..."); 

                        System.out.println("Connecting succesfully");
                        statement = connect.createStatement(); 
                        resultset = statement.executeQuery("select ProjName as 'Project Name', ProjID as 'Project ID' from projdetails");
                        //table.setModel(DBUtils.resultSetToTableModel(resultset));

                        ResultSetMetaData rsmetadata = resultset.getMetaData();
                        System.out.println(rsmetadata);
                        int columns = rsmetadata.getColumnCount();
                        System.out.println(columns);
                        DefaultTableModel dtm = new DefaultTableModel();
                        Vector columns_name = new Vector();
                        Vector data_rows = new Vector();
                        for ( int i =1; i<=columns;i++)
                        {
                    columns_name.addElement(rsmetadata.getColumnName(i));
                    System.out.println(columns_name);
                        }
                        dtm.setColumnIdentifiers(columns_name);

            //System.out.println(resultset);
            /*while(resultset.next())
            {
                    Array lastname = resultset.getArray("ProjName");
                    //lastname = 
                    System.out.println(lastname);
            }*/
            while ( resultset.next() )
            {

                data_rows = new Vector();
                for(int j =1; j<=columns; j++)
                { 
                    data_rows.addElement(resultset.getString(j));
                }

                dtm.addRow(data_rows);
            }
            table.setModel(dtm);

               /* final String lastName = resultset.getString("ProjName");
                //final String lastName1 = resultset.getString("ProjID");
                System.out.println(lastName);
                //System.out.println(lastName1);
                lbl_ShowAllProjects.setText(lastName);//+" "+lastName1);
                System.out.println("\n\n\t\t");*/



                }

            catch(Exception e){

                System.out.println("Cannot connect to database server");

                e.printStackTrace();
            }} 

            });
    btnOk.setBounds(94, 117, 89, 23);
    panel.add(btnOk);


    frame.getContentPane().add(panel_1, "name_762480663629692");
    panel_1.setLayout(null);


    table.setModel(new DefaultTableModel(
        new Object[][] {
        },
        new String[] {
            "Project Name", "Project ID"
        }
    ) {
        boolean[] columnEditables = new boolean[] {
            false, false
        };
        public boolean isCellEditable(int row, int column) {
            return columnEditables[column];
        }
    });
    table.getColumnModel().getColumn(0).setResizable(false);
    table.getColumnModel().getColumn(1).setResizable(false);
    table.setBounds(25, 11, 399, 216);
    panel_1.add(table);
    //final JScrollPane scrollPane = new JScrollPane(table);
    //JScrollPane scrollPane = new JScrollPane(table); 
    //panel_1.add(scrollPane);
    //table.setFillsViewportHeight(true); 
    //frame.getContentPane().add(new JScrollPane(table));
//  JScrollPane.setViewPortView(table);

}
1

There are 1 answers

0
Hovercraft Full Of Eels On

This is likely your culprit:

table.setBounds(25, 11, 399, 216);

You're artificially restricting the size of the JTable messing with its placement and rendering. So, yes, do put your JTable into a JScrollPane, and no, don't set the bounds of any component. You should avoid use of null layout and setBounds(...) with Java Swing programs as this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain (as you're finding out).

You can find links to the Swing tutorials, including the layout manager tutorials and other Swing resources here: Swing Info

Also, when changing a container's components, you will want to call revalidate() and repaint(). Better still would be to use a CardLayout to allow you to swap components.


e.g.,

import java.awt.*;
import java.awt.event.*;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class Foo {
   private static final String PANEL_KEY = "panel";
   private static final String PANEL_1_KEY = "panel 1";

   public static void main(String[] args) {
      final JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().setLayout(new CardLayout(0, 0));

      final JPanel panel = new JPanel();
      final JPanel panel_1 = new JPanel();
      final JTable table = new JTable();
      frame.getContentPane().add(panel, PANEL_KEY);
      frame.getContentPane().add(panel_1, PANEL_1_KEY);
      JButton btnOk = new JButton("ok");
      panel.add(btnOk);

      panel_1.setLayout(new BorderLayout());

      final JScrollPane scrollPane = new JScrollPane(table);
      panel_1.add(scrollPane);
      table.setFillsViewportHeight(true);
      frame.pack();
      frame.setVisible(true);

      btnOk.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            JPanel contentPane = (JPanel) frame.getContentPane();
            CardLayout cardLayout = (CardLayout) contentPane.getLayout();
            cardLayout.show(contentPane, PANEL_1_KEY);

            String[] colNames = { "Mon", "Tues", "Wed" };
            DefaultTableModel dtm = new DefaultTableModel();
            Vector<String> columns_name = new Vector<>();
            for (String colName : colNames) {
               columns_name.add(colName);
            }
            dtm.setColumnIdentifiers(columns_name);
            table.setModel(dtm);
         }
      });
   }

}