Assign column names to the JTable class

1

I have a simple application where an array of data passed to a JTable , I specify the names of the columns of the table, but only the data is displayed but not the names of the columns.

Here the code:

public class TableTest extends JFrame
{
    private String() columnNames = ("Planet", "Radius", "Moons", "Geseous", "Color");
    private Object[][] cells = 
    {
        {"Mercury", 2440.0, 0, false, Color.YELLOW},
        {"Venus", 6052 .0, 0, false, Color.YELLOW},
        {"Earth", 71492.0, 16, true, Color.BLUE},
        {"Mars", 3397.0, 2, false, Color.RED},
        {"Jupiter", 71492.0, 16, true, Color.ORANGE},
        {"Saturn", 60268.0, 18, true, Color.ORANGE},
        {"Uranus", 25559.0, 17, true, Color.BLUE},
        {"Neptune", 24766.0, 8, true, Color.BLUE},
        {"Pluto", 1137.0, 1, false, Color.BLACK}
    };

    public TableTest()
    {
        TableModel model = new DefaultTableModel (cells, columnNames);
        JTable table = new JTable (model);
        table. setAutoCreateRowSorter (true);
        add(table, BorderLayout.CENTER);
        JButton printButton = new JButton("Print");
        printButton.addActionListener.(
          EventHandler.create(ActionListener.class, table, "print")
        );
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(printButton);
        add(buttonPanel, BorderLayout.SOUTH);
        pack();
    };
};

How the table is displayed:

    
asked by David Leandro Heinze Müller 10.11.2016 в 19:57
source

1 answer

2

Add the JTable to a JScrollPane before to add it to JFrame .

add(new JScrollPane(table), BorderLayout.CENTER);

If you do not use a JScrollPane , according to the JTable documentation :

  

Note that if you want to use a JTable in a separate view (outside of JScrollPane ) and you want the header to appear, you can get it using getTableHeader() and display it separately.

TableModel modelo = new DefaultTableModel(cells,columnNames);
JTable table = new JTable(modelo);
/* Accedemos al header de forma individual */
JTableHeader header = tabla.getTableHeader();
add(table ,BorderLayout.CENTER);
add(header  ,BorderLayout.NORTH);
    
answered by 10.11.2016 / 20:08
source