Question

I want to add a scroll bar into my text area and I know the simple code for adding scroll bar but when I put the code for scroll bar the whole text area disappears!

What is the problem?

Here is my code:

private JFrame frame;
private JTextArea textarea;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {

                SmsForm window = new SmsForm();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public SmsForm() {
    initialize();
}

private void initialize() {
    frame = new JFrame("???");
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    JPanel groupBoxEncryption = new JPanel();

    final JTextArea textarea=new JTextArea();
    textarea.setBounds(50, 100, 300, 100);
    frame.getContentPane().add(textarea);
    textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

    JScrollPane scrollPanePlain = new JScrollPane(textarea);
    groupBoxEncryption.add(scrollPanePlain);
    scrollPanePlain.setBounds(100, 30, 250, 100);
    scrollPanePlain.setVisible(true);
Was it helpful?

Solution

There are a number of issues

  • You need to add the JPanel groupBoxEncryption to the application JFrame
  • Don't add the textarea to the frame - components can only have one parent component
  • As already mentioned, you're using null layout which doesnt size components - forget about not a layout manager.
  • As JPanel uses FlowLayout by default, you need to override getPreferredSize for the panel groupBoxEncryption. Better yet use a layout manager such as GridLayout that automatically sizes the component

Example

JPanel groupBoxEncryption = new JPanel(new GridLayout());

OTHER TIPS

  1. Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space.
  2. Suggest a preferred size for the text area in the number of rows and columns.
  3. Add the text area to a scroll pane before then adding the scroll pane to the GUI.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top