简体   繁体   中英

Column header not visible in Jtable

using the following code, can't manage to get the column headers to show..Added Jscroolpane as well,but no luck...

String[] col = {"COLA","COLB","COLC"};
Object[][] data = {};

DefaultTableModel model = new DefaultTableModel(data,col);


JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);

contentPane.add(table);
table.setBounds(295, 11, 512, 411);
contentPane.add(scrollPane,BorderLayout.CENTER);

When you construct the JScrollPane, you pass it the table, which is its only child component. But then you add the table to the contentPane, which means that you remove it from the JScrollPane and add it to the content pane. You must not add the table to the contentPane. Only the scrollPane, which itself contains the table.

Also, never use setBounds() . It makes no sense anyway since you're using a layout manager which takes care of positioning the components. And it makes even ess sense in this case since the table is handled by the JScrollPane.

This worked:

public static void main(String[] args) {
  String[] col = { "COLA", "COLB", "COLC" };
  Object[][] data = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
  DefaultTableModel model = new DefaultTableModel(data, col);
  JTable table = new JTable(model);
  JFrame frame = new JFrame();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(new JScrollPane(table));
  frame.setVisible(true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM