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();
}
}
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:
static
member variables is considered poor design null
layout). Use a layout manager instead JFrame
directly & use. ActionListeners
is to use either an anonymous instance or the Action interface. your StringBuilder is still null, when you want to write to it.
you need to instantiate your StringBuilder before appending.
s = new StringBuilder();
btw your StringBuilder s and your JScrollPane s have the same variable name, you should use different names.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.