Search code examples
javaeclipsejframejtextfield

How to use scrollbar for a JTextField in JAVA using eclipse GUI drag and drop tool?


I am using the eclipse GUI drag and drop tool. I have a JTextField in my program which shows content from a line in a textfile. Now, I want to add a horizontal scrollbar underneath the JTextField so that the user can view the content no matter how long it is.

I have the scrollbar and JTextField ready in my JFrame. Can someone provide me with guidance on how to link them please?

https://i.sstatic.net/ub9U5.jpg


Solution

  • Don't try to use a JTextField and a JScrollBar.

    Instead, use a JTextArea which is designed to work with a JScrollPane:

    JTextArea ta = new JTextArea(1, 10);
    ta.getDocument().putProperty("filterNewlines", Boolean.TRUE);
    JScrollPane sp = new JScrollPane( ta );
    sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    

    You need to reserve space for the scrollbar otherwise it will paint over top of the text. The scrollbar will be activated when required.

    This "filterNewLines" property just removes newline characters from the text so only a single line of text can be displayed in the text area.