cogm
cogm

Reputation: 285

Displaying a JTable Object

I'm trying to display a JTable in Java, but I can't get it to show up. I've tried a handful of different methods from different websites, and Java throws no errors - it just doesn't display. The other Swing elements do display so I'm not sure what the issue is.

public class MusicIO extends JFrame implements ActionListener{

    Container pane = this.getContentPane(); 
    JButton loadBtn, saveBtn;
    JTable table;

    public static void main(String[] args) {
        MusicIO music = new MusicIO();
        music.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        music.setSize(500, 500);
        music.init();
        music.setVisible(true);
    }

    public void init(){
        pane.setLayout(null);

        loadBtn = new JButton("Load from File");        
        loadBtn.setBounds(10, 10, 180, 30);
        loadBtn.addActionListener(this);
        pane.add(loadBtn);

        saveBtn = new JButton("Save to File");
        saveBtn.setBounds(290, 10, 180, 30);
        saveBtn.addActionListener(this);
        pane.add(saveBtn);

        displayDataInTable();
    }

    public void displayDataInTable(){
        String[] columns = {"Track Name", "Artist Name", "Album", "Length", "Year"};
        Object[][] data = {{"t", "a", "a", "1", "1"}};

        table = new JTable(data, columns);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        JScrollPane scrollPane = new JScrollPane(table);
        pane.add(scrollPane, BorderLayout.CENTER);
    }    
}

Upvotes: 0

Views: 39

Answers (1)

Damian Nikodem
Damian Nikodem

Reputation: 1289

You are not setting the location of the JScrollpane in your content pane appropriately.

if you simply added:

scrollPane.setBounds(50,50,50,50);

to the displayDataInTable() method you should be able to see that the scroll pane is being added, it was just not being positioned

I would STRONGLY recomend that you look up java layout managers and how to create Swing GUI's using nested JPanels. ( the official oracle/sun tutorials do a pretty good job at this. )

Upvotes: 1

Related Questions