开发者

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

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, Bord开发者_开发问答erLayout.CENTER);
        frame.add(panel);

        frame.setVisible(true);
    }

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


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


Interestingly the border disappears when you remove this line:

sp.setBorder(null);


I was looking for the answer for the same question but above answers could not do... so I found a better answer:

JScrollPane jsp = new JScrollPane();

//ur other codes

jsp.setViewportBorder(null);


For JTable table.setIntercellSpacing(new Dimension(0, 0)) works.


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


To remove the border from all parts of the JScrollPane including the vertical and horizontal bar the following code works

JScrollPane jsp = new JScrollPane();
jsp.getVerticalScrollBar().setBorder(null);
jsp.getHorizontalScrollBar().setBorder(null);
jsp.setBorder(null);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜