В следващия пример създадох две texFields. Докато пишете в първия текстов файл, ако интервалът или числото са въведени от потребителя, тогава трябва да се покаже съобщение в друго textField_1. Но след като потребителят въведе число/интервал, той дава java.lang.NullPointerException.
public class NewDemo extends JFrame {
private JPanel p1;
private JTextField textField,textField_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NewDemo frame = new NewDemo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public NewDemo() {
setTitle("New Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
p1 = new JPanel();
p1.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(p1);
p1.setLayout(null);
textField = new JTextField();
textField.setBounds(70, 71, 86, 20);
p1.add(textField);
textField.setColumns(10);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setBounds(70, 96, 86, 14);
p1.add(lblNewLabel);
textField_1 = new JTextField();
textField_1.setBounds(204, 71, 86, 20);
p1.add(textField_1);
textField_1.setColumns(10);
System.out.println("before calling");
((AbstractDocument) textField.getDocument()).setDocumentFilter(new MyDocumentFilter());
System.out.println("AfterCalling");
}
public JTextField getTextField_1() {
return textField_1;
}}
Ето втория клас MyDocumentFilter, където възниква грешката java.lang.NullPointerException в блока else на метода за замяна.
class MyDocumentFilter extends DocumentFilter {
private NewDemo n1;
@Override
public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
System.out.println("Starting: replace Method");
for (int n = string.length(); n > 0; n--)
char c = string.charAt(n - 1);
System.out.println(c);
if (Character.isAlphabetic(c)) {
System.out.println("In if: replace method");
super.replace(fb, i, i1, String.valueOf(c), as);
} else {
System.out.println("Not allowed:BEFORE");
n1.getTextField_1().setText("not allowed");//***HERE IS THE ERROR
System.out.println("Not allowed:AFTER");
}
}
}
@Override
public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {
System.out.println("In :remove method");
super.remove(fb, i, i1);
}
@Override
public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {
System.out.println("In: insterString Method");
super.insertString(fb, i, string, as);
}}