Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JScrollPane border overlaps on JTable border

I have a JTable inside a JScrollPane and I am trying to hide the ViewPortBorder of the JScrollPane. To do so I set its border to an empty border, but it looks like it paints the empty border on the JTable outer border (left border of the first column).

How can I hide the JScrollPane border without hiding the JTable border? The problem is only for the left side, the borders don't overlap on the right side.

public static void main(String[] args) {
    String[] columnNames = {"First Name",
            "Last Name",
            "Sport",
            "# of Years",
    "Vegetarian"};

    Object[][] data = {
            {"Kathy", "Smith",
                "Snowboarding", new Integer(5), new Boolean(false)},
                {"John", "Doe",
                    "Rowing", new Integer(3), new Boolean(true)},
                    {"Sue", "Black",
                        "Knitting", new Integer(2), new Boolean(false)},
                        {"Jane", "White",
                            "Speed reading", new Integer(20), new Boolean(true)},
                            {"Joe", "Brown",
                                "Pool", new Integer(10), new Boolean(false)}
    };

    JTable table = new JTable(data, columnNames);   
    JScrollPane scroll = new JScrollPane(table);

    Border border = BorderFactory.createEmptyBorder(0, 0, 0, 0);
    scroll.setViewportBorder(border);
    scroll.setBorder(border);

    JPanel panel = new JPanel();
    panel.add(scroll);

    JFrame frame = new JFrame();
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
}
like image 831
Julien Avatar asked Dec 11 '25 19:12

Julien


2 Answers

JTable doesn't have a border, what you're seeing is the border provided by the scroll pane

(Without border/with border)

enter image description here

This is actually (one of the reasons) why the left side of the table doesn't have a grid line ;)

What you could do is apply a MatteBorder to the table

Color color = table.getGridColor();
table.setBorder(new MatteBorder(0, 1, 0, 0, color));

(Without border/with border)

enter image description here

like image 63
MadProgrammer Avatar answered Dec 14 '25 09:12

MadProgrammer


You are correct when you set the JScrollPane border to an empty border. However, what you see on the left border of your table is simply the way that the JTable elements are drawn. You will notice that if you just add the JTable by itself without putting it into a scroll pane that it draws it exactly the same way.

If you want to draw a line on the left side of your table you have to manually set the border.

like image 36
David Yee Avatar answered Dec 14 '25 09:12

David Yee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!