views:

167

answers:

3

Hi All,

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));
}

}

A: 

Interestingly the border disappears when you remove this line:

sp.setBorder(null);
Guillaume
Not for me with windows XP. Maybe it's a platform issue.
Dan Howard
+1  A: 

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);
}
Sylvain M
Thanks! Looks fine now. :)
Dan Howard
Cool :). I think (but not sure) the default behavior of swing components is to have line border. So the BorderFactory class is your friend to customize them :)
Sylvain M
A: 

I think the proper fix is to set the border on the viewportView to 'null'.

RSC