Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set insets inside JScrollPane object?

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.

like image 331
tomas.teicher Avatar asked Aug 07 '12 08:08

tomas.teicher


People also ask

How do I add components to JScrollPane?

You can add components to the "view" at later stage if you want, but that's up to you... // Declare "view" as a class variable... view = new JPanel(); // FlowLayout is the default layout manager // Add the components you need now to the "view" JScrollPane scrollPane = new JScrollPane(view); view.

Can I add JPanel to JScrollPane?

We can also implement a JPanel with vertical and horizontal scrolls by adding the panel object to JScrollPane.

How do you create a scrollable text area in a Java Swing frame?

JFrame frame = new JFrame ("Test"); JTextArea textArea = new JTextArea ("Test"); JScrollPane scrollV = new JScrollPane (textArea); JScrollPane scrollH = new JScrollPane (textArea); scrollV. setVerticalScrollBarPolicy(JScrollPane. VERTICAL_SCROLLBAR_ALWAYS); scrollH. setHorizontalScrollBarPolicy(JScrollPane.


1 Answers

Update: From your updated question I reckon that you are actually after JComponent.setBorder, example screenshot:

screenshot border

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:

screenshot viewport border

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);
}
like image 160
dacwe Avatar answered Sep 23 '22 00:09

dacwe