0
votes

I have created a JScrollbar (with a custom UI) and a JTextArea in a JScrollPane in a JPanel. I don't want to add the scrollbar as the scrollpane's horizontal scrollbar, because I want to be able to position it.

I tried setting the model on the scrollbar and adding it to the panel (see code), but this didn't work -- the thumb didn't size correctly (it always spanned the entire track) and wasn't positioned correctly.

JPanel panel = new JPanel();
JTextArea textArea = new JTextArea(col, rows);
JScrollPane scrollPane = new JScrollPane(textArea);
JScrollBar scrollBar = new JScrollBar();    
scrollBar.setModel(scrollPane.getHorizontalScrollBar().getModel());
panel.add(textArea);
panel.add(scrollPane);
panel.add(scrollBar)

How can I link a scrollbar to my text area so the thumb sizes and behaves correctly and still be able to set the position and dimensions of my scrollbar?

Thanks!

1
What do you mean by "link a scrollbar to my text area"? Are you trying to display value of horizontal scrollbar in textArea? Does it need to be JScrollBar in your panel (there is JSlider probably more suited for this). - Xeon
I want the scroll bar to dictate what is visible (horizontally) in my scrollpane and the thumb to scale based on how much is visible in the scrollpane (similar to the default behavior for a JScrollPane's default JScrollBars). Does that make sense? - user1555349

1 Answers

0
votes

If you want the default behaviour - you did it already. You need to add some components to your JScrollPane to actually see it.

Below is an example:

public final class Test {
    public static void main(String[] a) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                Container pane = frame.getContentPane();
                JPanel panel = new JPanel();
                JTextArea textArea = new JTextArea(2, 10);
                JScrollPane scrollPane = new JScrollPane(textArea);
                JScrollBar scrollBar = new JScrollBar();//new JScrollBar(SwingConstants.HORIZONTAL);
                scrollBar.setModel(scrollPane.getHorizontalScrollBar().getModel());
                panel.add(textArea);
                panel.add(scrollPane);

                JPanel internal = new JPanel();
                for(int i = 0; i < 20; ++i) {
                    internal.add(new JLabel("TEXT"));
                }
                scrollPane.setViewportView(internal);
                scrollPane.setPreferredSize(new Dimension(100, 100));
                panel.add(scrollBar);
                pane.add(panel);
                frame.pack();
                frame.setLocationRelativeTo(null);

                frame.setVisible(true);
            }
        });
    }
}