Search code examples
javaswingjtextareastringbuilder

Read text in JTextArea into StringBuilder


I try to read all lines in the text area into StringBuilder so that I can use the text in text area as a whole string. However I get the NullPointerException in line s.append(line);. Why?

public class tu extends JFrame implements ActionListener{

    JTextArea t;
    static StringBuilder s;

    tu (){

        setLayout(/*new BorderLayout()*/null);
        t=new JTextArea(30,77);
        JScrollPane s=new JScrollPane(t,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        JButton b=new JButton("process");
        b.addActionListener(this);
        JPanel p=new JPanel();
        JPanel p1=new JPanel();
        p.add(s);
        p.setBorder(new TitledBorder("sequence"));
        p.setBounds(0,0,880,540);
        p1.add(b);
        p1.setBounds(380,570,100,40);
        add(p);
        add(p1);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(900,700);
        setVisible(true);

    }
     public void actionPerformed(ActionEvent e){
         String text=t.getText();
         while (text!=null){for (String line : text.split("\\n")){ 
         s.append(line);
         }}

     }


    public static void main(String[] args){
        tu t=new tu();

    }
}

Solution

  • Attempting to invoke any method on an object that has not been instantiated will result in an NPE. You need to instantiate your StringBuilder s:

    StringBuilder s = new StringBuilder();
    

    Do you really want to wait until the user has clicked the JButton before building up the contents of this StringBuilder? StringBuilders are typically used as on-demand helper objects with local scope.


    A number of things to note:

    • Use of static member variables is considered poor design
    • Class names start with uppercase letters
    • Don't use absolute positioning(null layout). Use a layout manager instead
    • The preferred approach is to create an instance of JFrame directly & use.
    • The preferred approach for ActionListeners is to use either an anonymous instance or the Action interface.
    • Consider using initial threads