JTable table = new JTable(data,columnNames);
JScrollPane pane = new JScrollPane(table);
this.add(pane);
this.add(table);
My data is showing but column name is not showing on top.
JTable table = new JTable(data,columnNames);
JScrollPane pane = new JScrollPane(table);
this.add(pane);
this.add(table);
My data is showing but column name is not showing on top.
A component can only have a single parent.
JScrollPane pane = new JScrollPane(table);
this.add(pane);
this.add(table);
First you add the table to the viewport of the scrollpane, which is good as this will cause the table header to automatically be displayed when the GUI is made visible.
But then you add the table directly to the frame, which is bad because it can no longer be displayed in the scrollpane.
Get rid of:
//this.add(table);
and then the scrollpane containing the table will be displayed properly on the frame.
Have a look at this example
import java.awt.Color;
import javax.swing.*;
public class table extends JFrame{
public table() {
setSize(600, 300);
String[] columnNames = {"A", "B", "C"};
Object[][] data = {
{"Moni", "adsad", 2},
{"Jhon", "ewrewr", 4},
{"Max", "zxczxc", 6}
};
JTable table = new JTable(data, columnNames);
JScrollPane tableSP = new JScrollPane(table);
JPanel tablePanel = new JPanel();
tablePanel.add(tableSP);
tablePanel.setBackground(Color.red);
add(tablePanel);
setTitle("Marks");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
table ex = new table();
ex.setVisible(true);
}
});
}
}