How to set insets inside JScrollPane object?
-
25-06-2021 - |
Question
I have JScrollPane which contains only one instance of JTree. How can I set margin around JTree inside of JScrollPane?
I have such a code
tree.setPreferredSize(new Dimension(200, 200));
JScrollPane scrollerTree = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollerTree.setPreferredSize(new Dimension(200, 199));
scrollerTree.getVerticalScrollBar().setUnitIncrement(16);
I want to achieve, that margin would be scrollable with scrollpane content.
Solution
Update: From your updated question I reckon that you are actually after JComponent.setBorder
, example screenshot:
Code:
public static void main(String[] args) {
JTree tree = new JTree();
tree.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JFrame frame = new JFrame("Test");
frame.add(new JScrollPane(tree));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
Original answer, if you want a border around the view port, use JScrollPane.setViewportBorder
:
Code:
public static void main(String[] args) {
JScrollPane scroll = new JScrollPane(new JTree());
scroll.setViewportBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JFrame frame = new JFrame("Test");
frame.add(scroll);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow