好的,这是我和我一起工作的班级。
问题出在write()方法中,在那里我抛出了一个NPE ...我不明白如何访问这个文本区域,我只是想简单地添加文本到最后它!
public class chatBox extends JPanel implements ActionListener{
protected static JTextField textField;
protected static JTextArea textArea;
private final static String newline = "\n";
public static int tick = 0;
public chatBox() {
super(new GridBagLayout());
textField = new JTextField(25);
textField.addActionListener(this);
textArea = new JTextArea(5, 25);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Add Components to this panel.
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.VERTICAL;
c.weighty = 0.5;
c.weightx = 0.5;
c.fill = GridBagConstraints.VERTICAL;
add(textField, c);
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 0;
c.weighty = 0.1;
c.gridx = 0;
c.gridy = 1;
add(scrollPane, c);
}
public void actionPerformed(ActionEvent evt) {
String text = textField.getText();
textArea.append(Commands.cmd(text) + newline);
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
//textArea.setCaretPosition(textArea.getDocument().getLength());
}
public static void write(String wstr) {
System.out.println("Writing " + wstr);
textArea.append(wstr + newline);
}
答案 0 :(得分:0)
您需要创建一个chatBox
对象才能初始化textArea
。之后,您可以调用静态方法write。
或者您可以在静态块中初始化静态属性:
static {
textArea = ....
}