Reputation: 17
I try to create a JTable
with the column names "User" and with the test data "data", but the column names do not get printed.
String [] [] data = {{"hallo","hallo","","","",""},
{"hallo","hallo","","","",""}};
String [] User = {"ID","Benutzername", "Name", "Vorname", "Geburtsdatum", "Wirt"};
tableUsers = new JTable(data,User);
tableUsers.setPreferredScrollableViewportSize(new Dimension(500,50));
tableUsers.setFillsViewportHeight(true);
//add(new JScrollPane(tableUsers));
JTableHeader header = tableUsers.getTableHeader();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(header, BorderLayout.NORTH);
panel.add(tableUsers, BorderLayout.CENTER);
JScrollPane scrollPane = new JScrollPane(tableUsers);
add(scrollPane);
tableUsers.setBounds(29, 245, 580, 136);
contentPane.add(tableUsers);
Upvotes: 0
Views: 204
Reputation: 324207
JTable does not show column names - JScrollPane used
You are not using the JTable and JScrollPane correctly.
The basic code should be:
JTable table = new JTable(...);
JScrollPane scrollPane = new JScrollPane( table );
frame.add(scrollPane);
That is there is no need to:
Upvotes: 1
Reputation: 1847
You add your table to the JPanel panel, then you add panel to the scroll pane. So, now your scroll pane contains your table. Now, you need to add the scroll pane to the content pane. You should not be adding your tableUsers to multiple items.
Edit: I am adding my entire code I used to run and test since I think you're having a separate issue.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
public class Test {
/**
* Do this for thread safety
* @param args
*/
public static void main (String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
/**
* create the JFrame
*/
private static void createGUI() {
JFrame jf = new JFrame();
addComponents(jf.getContentPane());
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
}
/**
* add the components
* @param pane
*/
private static void addComponents(Container pane) {
String [] [] data = {{"hallo","hallo","","","",""}, {"hallo","hallo","","","",""}};
String [] User = {"ID","Benutzername", "Name", "Vorname", "Geburtsdatum", "Wirt"};
JTable tableUsers = new JTable(data,User);
tableUsers.setPreferredScrollableViewportSize(new Dimension(500,50));
tableUsers.setFillsViewportHeight(true);
//add(new JScrollPane(tableUsers));
JTableHeader header = tableUsers.getTableHeader();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(header, BorderLayout.NORTH);
panel.add(tableUsers, BorderLayout.CENTER);
JScrollPane scrollPane = new JScrollPane(panel);
pane.add(scrollPane);
tableUsers.setBounds(29, 245, 580, 136);
//pane.add(tableUsers);
}
}
Upvotes: 1