Search code examples
javajtextarea

How to restrict user input in JTextArea?


Currently I have a text area with a few menu choices with a scroll bar for when I add more items. This displays fine, but the user is able to type in this textarea and change the contents of the menu. How can I restrict them from typing?

import java.awt.*;
import javax.swing.*;

    JFrame frame;
    frame = new JFrame();
    frame.setSize(1000, 900);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);



    JPanel VendingSelection = new JPanel();
    VendingSelection.setBounds(0, 0, 984, 865);
    frame.getContentPane().add(VendingSelection);
    VendingSelection.setLayout(null);

    JTextArea txtArea = new JTextArea();
    txtArea.setText("Hamburger,5.00,6\n"
            +       "Fries,2.25,7\n"
            +       "Hotdog,3,10");
    VendingSelection.add(txtArea);
    JScrollPane scroll = new JScrollPane(txtArea);
    scroll.setBounds(534, 89, 334, 654);
    VendingSelection.add(scroll);

Solution

  • To make the JTextArea not editable call the setEditable() method and pass a false value as the parameter.