38

如果您运行下面的小示例,您将看到中心区域周围的边框。我不确定为什么会显示此边框。

当 JTable 在 JScrollPane 中时会发生这种情况。我尝试了各种方法来删除它,但到目前为止还没有运气。没有 JScrollPane 的 JTable 不显示边框。

请参阅下面的示例。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));
    }
}
4

6 回答 6

67

使用 BorderFactory.createEmptyBorder() 而不是 null...

通过使用:

sp.setBorder(createEmptyBorder());

有用。

您的主要方法变为:

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);
}
于 2010-07-26T09:40:31.517 回答
6

我一直在寻找同一个问题的答案,但上面的答案做不到......所以我找到了一个更好的答案:

JScrollPane jsp = new JScrollPane();

//ur other codes

jsp.setViewportBorder(null);
于 2013-06-01T13:18:32.813 回答
5

有趣的是,当您删除此行时,边框会消失:

sp.setBorder(null);
于 2010-07-26T09:38:33.143 回答
1

对于 JTabletable.setIntercellSpacing(new Dimension(0, 0))工作。

于 2015-09-24T07:57:08.240 回答
1

要从 JScrollPane 的所有部分(包括垂直和水平条)中删除边框,以下代码有效

JScrollPane jsp = new JScrollPane();
jsp.getVerticalScrollBar().setBorder(null);
jsp.getHorizontalScrollBar().setBorder(null);
jsp.setBorder(null);
于 2020-08-05T18:48:53.413 回答
0

我认为正确的解决方法是将 viewportView 上的边框设置为“null”。

于 2010-08-19T18:36:26.713 回答