[英]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 . 我尝试将文本区域中的所有行读入StringBuilder,以便可以将文本区域中的文本用作整个字符串 。 However I get the NullPointerException in line s.append(line); 但是我在s.append(line);行中得到了NullPointerException ; . 。 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
. 尝试在尚未实例化的对象上调用任何方法将导致NPE
。 You need to instantiate your StringBuilder
s
: 您需要实例化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
? 您是否真的要等到用户单击JButton
才构建此StringBuilder
的内容? StringBuilders
are typically used as on-demand helper objects with local scope. StringBuilders
通常用作具有局部范围的按需帮助对象。
A number of things to note: 需要注意的一些事情:
static
member variables is considered poor design 使用static
成员变量被认为是不良设计 null
layout). 不要使用绝对定位( null
布局)。 Use a layout manager instead 改用布局管理器 JFrame
directly & use. 首选方法是直接创建并使用JFrame
的实例。 ActionListeners
is to use either an anonymous instance or the Action interface. ActionListeners
的首选方法是使用匿名实例或Action接口。 your StringBuilder is still null, when you want to write to it. 当您要写入StringBuilder时,它仍然为null。
you need to instantiate your StringBuilder before appending. 您需要在追加之前实例化StringBuilder。
s = new StringBuilder();
btw your StringBuilder s and your JScrollPane s have the same variable name, you should use different names. 顺便说一下,您的StringBuilder和JScrollPane具有相同的变量名,您应该使用不同的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.