The problem is not the table or the jscrollpane but how you put them in the panel:
panel.add(scrollPane);
panel.add(titleLabel);
panel.add(scheduleTable);
First of all the scheduleTable is (visually) inside the scrollPane, so you only need to put the scrollPane, not the table again. So we want:
panel.add(titleLabel); //first put the title
panel.add(scrollPane);
this works nicely:
And when I say it works nicely I mean it works nicely... by chance. The real layout of the elements is discovered when you make the window bigger:
The problem is in this code again:
panel.add(titleLabel); //first put the title
panel.add(scrollPane);
This surely adds the components (label and scrollpane) to the panel, however the obvious question is "Where in the panel adds them?".
Then answer is that the panel has a LayoutManager that decides the position of its components. There are several of them, you have to pick one, learn how it works and use it, look at this visual guide.
Because you didn't specify a layout, the panel
is using the default layout for panels FlowLayout
, that puts the components one after the other, side by side.
Pick a layout look at the tutorial and then use it. For example I could use a BorderLayout like this:
JPanel panel = new JPanel(new BorderLayout());
...
panel.add(titleLabel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
Gives:
Full code:
String[] columnNames = {"Date","Field", "Home Team","Visitor Team", "Score"};
JFrame guiFrame = new JFrame(); //no layout specified, frames use BorderLayout by default
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Soccer Schedule");
guiFrame.setSize(500,500);
guiFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel(new BorderLayout());
panel.setSize(450, 450);
JLabel titleLabel = new JLabel("Real Tired");
//String[][] data = createTableContents(scheduleCsv);
//my test data
String[][] data = new String[1][5];
for (int i = 0; i < 5; ++i)
{
data[0][i] = "cell " + i;
}
JTable scheduleTable = new JTable(data,columnNames);
JScrollPane scrollPane = new JScrollPane(scheduleTable);
panel.add(titleLabel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
guiFrame.add(panel); //this is actually guiFrame.add(panel, BorderLayout.CENTER);
guiFrame.setVisible(true);