1

For some reason my JTable is not displaying it's column names?! I'm certain I've done everything correctly. I've literally copied this from a demonstration so I don't understand why it won't work.

Here is my code:

public class MemTableModel extends AbstractTableModel{
    private ArrayList<member> members = new ArrayList<member>();
    private String[] columnNames = {"ID", "Name", "Email", "Country", "Genre",
            "Gender", "Description", "Type", "Limit", "Card No", "Expiry Date"};

    public MemTableModel(){
        LoadTableFromDB();
    }
    public int getRowCount(){
        return members.size();
    }
    public int getColumnCount(){
        return columnNames.length;
    }

    public Object getValueAt(int row, int col){
        //Get the row from the about get method
        member f = members.get(row);
        switch(col){
            case 0: return f.getmembId();
            case 1: return f.getname();
            case 2: return f.getemail();
            case 3: return f.getcountry();
            case 4: return f.getfavGenre(); 
            case 5: return f.getgender();
            case 6: return f.getdescription();
            case 7: return f.getmemberType();
            case 8: return f.getsongLimit();
            case 9: return f.getcard_no();
            case 10: return f.getexpiry_date();
        }
        return null;
    }
    public String getColumnName(int col){
        return columnNames[col];
    }

    public member getRow(int row){
        member c = members.get(row);
        return c;
    }
    public Connection getConnection(){
        Connection conDB = null;
         /****** DEFAULT MYSQL DRIVERS **************************/
            String url = connection.geturl();
            String username = connection.getUsername();
            String password = connection.getPassword();
        try{
            //load the MYSQL driver
            Class.forName(connection.getDriver());
            conDB = DriverManager.getConnection(url, username, password);
        }
        catch(Exception e){

        }
         return conDB;
    }
    //Load all DB values into ARRAY
    public void LoadTableFromDB(){
        Connection conDB = null;
        Statement stmt = null;
        ResultSet r = null;
        try{
            //Connection + Statement
            conDB = getConnection();
            stmt = conDB.createStatement();
            //Queries
            String sqlSelectAll = "SELECT * FROM members";
            r = stmt.executeQuery(sqlSelectAll);

            members.clear();
            //Loop through the resultset
            while(r.next()){
            members.add(new member(r.getInt("membId"), r.getString("name"), 
                r.getString("email"), r.getString("country"), r.getString("favGenre"),
                r.getString("gender"), r.getString("description"), r.getString("memberType"),
                r.getString("songLimit"), r.getString("card_no"), r.getString("expiry_date")));
            }
            conDB.close();  // Close the DB connection

        }//End of TRY
        catch(Exception er){
            System.out.println("Error was: " + er);
        }
    }
}

Here is how I've implemented the JTable:

public class ViewAll extends JFrame implements ActionListener{
    //Jtextfields, buttons, labels
    private JButton btnBack = new JButton("Back");

    private static JLabel lblMembTitle = new JLabel("<html><h1>All Members</h1></html>");
    private static JLabel lblPlayTitle = new JLabel("<html><h1>All Playlists</h1><br /></html>");
    //Containers, Panels, Scrollpanes
    private Container mainCon = this.getContentPane();
    private static JPanel pnlTable = new JPanel(new BorderLayout());

    //Jpanels - sections
    private JPanel mainPanel = new JPanel();
    private JPanel subPanel1 = new JPanel();
    private JPanel subPanel2 = new JPanel();
    private JPanel subPanel3 = new JPanel();

    //Tables
    private static JTable tblShowAllMemb = new JTable();
    private static JTable tblShowAllPlay = new JTable();
    JScrollPane scrollPane = new JScrollPane(mainPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    public ViewAll(){
        super("Search/Edit/Delete Members");
        this.setBounds(400, 800, 854,400);
        this.setVisible(true);
        mainCon.add(scrollPane);

        //Table Models:
        MemTableModel tblMembers = new MemTableModel();
        PlayTableModel tblPlaylist = new PlayTableModel();

        //LAYOUT
        /*By removing this the scrollpane works
            ^^mainPanel is already added to the scrollPane object above ^^
        */
//        mainCon.add(mainPanel);

        //Main Panel
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(BorderLayout.NORTH, subPanel1);
        mainPanel.add(BorderLayout.CENTER, subPanel2);

        //Panel1 - Member table + Back Button
        subPanel1.setLayout(new BorderLayout());
        subPanel1.add(BorderLayout.NORTH, btnBack);
        subPanel1.add(BorderLayout.CENTER, lblMembTitle);
        subPanel1.add(BorderLayout.SOUTH, tblShowAllMemb);
        tblShowAllMemb.setModel(tblMembers);
        btnBack.addActionListener(this);



        //Panel2 - Playlist table
        subPanel2.add(BorderLayout.NORTH, lblPlayTitle);
        subPanel2.add(BorderLayout.CENTER, tblShowAllPlay);
        tblShowAllPlay.setModel(tblPlaylist);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == btnBack){
            this.dispose();
        }
    }

}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
James111
  • 15,378
  • 15
  • 78
  • 121
  • Then do you have a public link from that demonstration ? What did you do besides copy and paste the code ? – nha Jun 13 '15 at 11:50
  • The likely issue is you've not wrapped the `JTable`, which represents your `TableModel` in a `JScrollPane` as demonstrated in [How to Use Tables](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) – MadProgrammer Jun 13 '15 at 11:52
  • 1
    @MadProgrammer - I updated my Question (Added in how I used it). I've wrapped the `panel (mainPanel)` in the `ScrollPane` then added the `ScrollPane` to the `container (mainCon)` – James111 Jun 13 '15 at 11:55
  • 2
    No, you need to wrap the `JTable` itself inside a `JScrollPane`, not within a component that's within a scroll pane – MadProgrammer Jun 13 '15 at 11:57
  • 1
    Ohh. Awesome! That fixed it @MadProgrammer – James111 Jun 13 '15 at 11:59

1 Answers1

2

The likely issue is you've not wrapped the JTable, which represents your TableModel in a JScrollPane as demonstrated in How to Use Tables

By simply using something like...

add(new JScrollPane(new JTable(new MemTableModel())));

I can get:

Example

See also How to Use Scroll Panes for more details

Updated based on updated code...

Not one of your tables is actually wrapped within it's own JScrollPane

// By the way, static here is very, very bad idea
private static JTable tblShowAllMemb = new JTable();
private static JTable tblShowAllPlay = new JTable();
JScrollPane scrollPane = new JScrollPane(mainPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

public ViewAll(){
    //....

    //Table Models:
    MemTableModel tblMembers = new MemTableModel();
    PlayTableModel tblPlaylist = new PlayTableModel();

    //...
    subPanel1.add(BorderLayout.SOUTH, tblShowAllMemb);

    //...
    subPanel2.add(BorderLayout.CENTER, tblShowAllPlay);

You've just added the table by itself to some other container. Instead, consider using something like

//...
subPanel1.add(BorderLayout.SOUTH, new JScrollPane(tblShowAllMemb));

//...
subPanel2.add(BorderLayout.CENTER, new JScrollPane(tblShowAllPlay));
Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • 1
    This worked! Awesome, saved me a lot of time. The last couple of days I've known nothing about `scrollpanes` but now Im getting my head around them! – James111 Jun 13 '15 at 11:59
  • 1
    Is there a reason why the `Table` is taking up more room than it should? It's only got 3 rows and it's taking up half the page with a `white background`. Not a problem but wondering why this woiuld be happening? – James111 Jun 13 '15 at 12:03
  • 1
    `JTable` implements the `Scrollable` interface, which provides a `getPreferredScrollableViewportSize` which is used by the `JScrollPane` to make determinations about it's preferred size. By default, `JTable` returns a size of `450x400`, which can be a tad large sometimes. Unusually, it also provides `setPreferredScrollableViewportSize` which allows you to change it, although I think something like `setVisibleRowCount` would have been preferred :{ – MadProgrammer Jun 13 '15 at 12:06
  • 1
    This code here worked for setting the correct height! Although I imagine if the table has 100 rows then It may just keep going and going. `table.setPreferredScrollableViewportSize(table.getPreferredSize()); table.setFillsViewportHeight(true);` – James111 Jun 13 '15 at 12:17
  • Yeah, I'd be careful with it, you might use something like `JTable#getRowHeight` and multiple by your preferred number of visible rows and cross reference with the width from `getPreferredScrollableViewportSize` – MadProgrammer Jun 13 '15 at 12:19