How to get rid of the border with a JTable / JScrollPane

sproketboy picture sproketboy · Jul 26, 2010 · Viewed 29.5k times · Source

If you run the small sample below you'll see a border around the center region. I'm not sure why this border is showing.

It happens when a JTable is in a JScrollPane. I tried various things to remove it but so far no luck. A JTable without the JScrollPane shows no border.

See sample below. TIA.

public class TestScrollPane extends JFrame {

    public static void main(String[] args) {
        JFrame frame = new TestScrollPane();
        JPanel panel = new JPanel();
        JTable table = new JTable();

        panel.setLayout(new BorderLayout());
        panel.add(new JLabel("NORTH"), BorderLayout.NORTH);
        panel.add(new JLabel("SOUTH"), BorderLayout.SOUTH);

        JScrollPane sp = new JScrollPane(table);
        // None of these have any effect
        sp.setBorder(null);
        sp.getInsets().set(0, 0, 0, 0);
        sp.setViewportBorder(null);
        sp.getViewport().setBorder(null);
        sp.getViewport().getInsets().set(0, 0, 0, 0);
        sp.getViewport().setOpaque(true);

        panel.add(sp, BorderLayout.CENTER);
        // Adding the table alone shows no border
        // panel.add(table, BorderLayout.CENTER);
        frame.add(panel);

        frame.setVisible(true);
    }

    public TestScrollPane() throws HeadlessException {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setMinimumSize(new Dimension(100, 100));
    }
}

Answer

sly7_7 picture sly7_7 · Jul 26, 2010

Use BorderFactory.createEmptyBorder() instead of null...

by using:

sp.setBorder(createEmptyBorder());

it works.

Your main method becomes:

public static void main(String[] args) {
    JFrame frame = new TestScrollPane();
    JPanel panel = new JPanel();
    JTable table = new JTable();

    panel.setLayout(new BorderLayout());
    panel.add(new JLabel("NORTH"), BorderLayout.NORTH);
    panel.add(new JLabel("SOUTH"), BorderLayout.SOUTH);

    JScrollPane sp = new JScrollPane(table);
    sp.setBorder(BorderFactory.createEmptyBorder());
    panel.add(sp, BorderLayout.CENTER);
    frame.add(panel);

    frame.setVisible(true);
}