简体   繁体   中英

Linking a Java JScrollBar to a JTextArea/Custom positioning a JScrollBar (track and thumb)

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!

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);
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM