0

I am making a JTable and I am having 2 problems. #1 the table headers are showing up on the side of the table and #2 the scroll pane isn't showing up. This is some of my code right now.

String [] data = {"a", "b", "c", "d", "e"};
JFrame frame = new JFrame("String Table");
JPanel middlePanel = new JPanel();              
DefaultTableModel model = new DefaultTableModel();
model.addColumn("String", data);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);    


frame.getContentPane().add(middlePanel, BorderLayout.CENTER);
middlePanel.add(scrollPane);
middlePanel.add(table.getTableHeader());
middlePanel.add(table);


frame.setSize(400, 200);
frame.setVisible(true);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
user2007843
  • 609
  • 1
  • 12
  • 30

1 Answers1

2
  1. use only code line middlePanel.add(scrollPane);

  2. JPanel (middlePanel) should be layed by GridLayout or BorderLayout

  3. remove code lines middlePanel.add(table.getTableHeader()); and middlePanel.add(table);

  4. move code line frame.getContentPane().add(middlePanel, BorderLayout.CENTER); after middlePanel.add(scrollPane);, and could be frame.add(middlePanel); if isn't changed LayoutManager for JFrame

  5. remove frame.setSize(400, 200); replace with frame.pack() and to determine proper PreferredSize by override getPreferredSize for JScrollPane

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • I ran into another issue. My table is showing up really small and the elements in the first column are quite long, so I need to extend both the table and column 1 – user2007843 Apr 17 '13 at 17:47
  • more ideas about to see [here](http://stackoverflow.com/a/10089138/714968) and [here](http://stackoverflow.com/a/9164884/714968) – mKorbel Apr 17 '13 at 18:00