Home > front end >  Scroll for GUI not working the way I want it to
Scroll for GUI not working the way I want it to

Time:11-18

I am trying to get this textarea on this GUI to have a scroll, but when I try to add it either the text area covers the scroll bar or vice versa. No errors. Code:

        // Text Area at the Center
        JTextArea ta = new JTextArea ( 16, 58 );
        ta.setEditable ( false ); // set textArea non-editable
        JScrollPane scroll = new JScrollPane ( ta );
        scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
        
        send.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent send) {
                String data = tf.getText();
                ta.append("You: "   data   "\n");
                tf.setText("");
                System.out.println(data);
            }
        });
        
        //Adding Components to the frame.
        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.getContentPane().add(BorderLayout.CENTER, ta);
        frame.add(ta);
        ta.add(scroll);
        frame.setVisible(true);

CodePudding user response:

These lines are the issue:

frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.add(ta);
ta.add(scroll);

Don't add the JTextArea to your frame, as the JTextArea is already correctly configured to be inside the viewport of the JScrollPane (since you supplied it to the scrollpanes constructor earlier). Also you're not supposed to add the JScrollPane to the JTextArea, because you want it the other way around. The correct approach would be to remove the mentioned lines and to simply add scroll to your JFrame, like so:

frame.add(BorderLayout.CENTER, scroll);

Sidenote:

  • as mentioned in the comments, consider calling pack() on your frame before setting it visible, to size the frame and its components correctly.
  • Related