如何摆脱JTable/JScrollPane的边界

spr*_*boy 36 java swing jtable jscrollpane

如果您运行下面的小样本,您将看到中心区域周围的边框.我不确定为什么会出现这种边界.

当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));
    }
}
Run Code Online (Sandbox Code Playgroud)

sly*_*7_7 61

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

通过使用:

sp.setBorder(createEmptyBorder());
Run Code Online (Sandbox Code Playgroud)

有用.

你的主要方法是:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 请参阅下面的克里希纳答案:`sp.setViewportBorder(null);` (2认同)

Kri*_*pta 6

我正在为同一个问题寻找答案,但上面的答案却无法做到......所以我找到了一个更好的答案:

JScrollPane jsp = new JScrollPane();

//ur other codes

jsp.setViewportBorder(null);
Run Code Online (Sandbox Code Playgroud)


Gui*_*ume 5

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

sp.setBorder(null);
Run Code Online (Sandbox Code Playgroud)