0

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

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 3
    1) Yes, put your JTable into a JScrollPane. 2) Get rid of **all** `setBounds(...)` and null layouts in your program since they will make it difficult for Java to size your JTable and the JScrollPane correctly. Instead use the layout managers as that's what they're for. 3) Let's see your best attempt on how to do this with JScrollPanes as a [Minimal, Complete, and Verifiable Example Program](http://stackoverflow.com/help/mcve). Your commented code contains some non-compilable code. – Hovercraft Full Of Eels Nov 23 '14 at 15:05
  • 1
    You need to use a JScrollPane. Not using one won't make it work better. Post a complete example reproducing the problem. Remove all the irrelevant JDBC stuff from it. – JB Nizet Nov 23 '14 at 15:06

1 Answers1

2

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

}
Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373