Search code examples
javaswinguser-interfacejtablejscrollpane

How do I remove the A on the top of the JTable inside a JScrollPane?


Why is there an A on the top of the table?

I placed a JTable inside a JScrollPane to make it scrollable. Are there methods that I need to place? I did not place a letter A though so I cant track.

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.JTable;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

public class Rawr {

    private JFrame frame;
    private JScrollPane scrollPane;
    private JTable table;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Rawr window = new Rawr();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Rawr() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        frame.getContentPane().add(panel, BorderLayout.CENTER);
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        scrollPane = new JScrollPane();
        scrollPane.setToolTipText("");
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        panel.add(scrollPane);

        table = new JTable(100, 1);
        table.setBorder(new LineBorder(new Color(0, 0, 0)));
        scrollPane.setViewportView(table);
    }
}

How do I remove it? Thanks!


Solution

  • Set the column name explicitly using:

    String[] colNames = new String[]{"Your Column Name"};
    DefaultTableModel defaultTableModel = new DefaultTableModel(colNames, 100);
    table = new JTable(defaultTableModel);
    

    If you create a table using new JTable(100, 1) you will see the A, B and so on column headers because the constructor javadoc says:

    Constructs a JTable with numRows and numColumns of empty cells using DefaultTableModel.

    Since the JTable constructor does not have any information about the column headers. It can only create a DefaultTableModel that does not know any column header names. The DefaultTableModel extends AbstractTableModel and the javadoc of AbstractTableModel.getColumnName() says

    Returns a default name for the column using spreadsheet conventions: A, B, C, ... Z, AA, AB, etc. If column cannot be found, returns an empty string.