I keep getting an NullPointerException, and I dont know why. what the class is supposed to do, is to send whatever I write in my jtextfield as writeUTF, but I keep getting a NullPointerException at
dos = new DataOutputStream(socket.getOutputStream());
The GUI code:
public class GUI {
private JFrame frame = new JFrame("Dryck & Ingrediens"); // GUI
private JTextField jtf = new JTextField();// GUI
private JTextArea jl1 = new JTextArea();// GUI
private JList jl = new JList();// GUI
private JScrollPane js = new JScrollPane(jl);// GUI
private DataOutputStream dos;// ServerHandler
private JLabel lab = new JLabel("Ange dryck");//GUI
private JLabel lab1 = new JLabel("Walid Shams");
private JLabel lab2 = new JLabel("Kushtrim Brahimi");
private HashMap<String, ArrayList<String>> drinkar = null;//Controller
private DataInputStream dis;
private Socket socket;
private ServerHandler serverH;
public GUI() {
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(50, 300, 420, 400);
frame.setResizable(false);
frame.setVisible(true);
js.add(jl);
js.add(jl1);
jl1.setEditable(false);
lab.setBounds(170, 20, 130, 20);
lab1.setBounds(300, 310, 130, 20);
lab2.setBounds(300, 330, 130,20);
jtf.setBounds(130, 40, 150, 40);
jl.setBounds(50, 90, 150, 200);
jl1.setBounds(210, 90, 150, 200);
Container con = frame.getContentPane();
con.setBackground(Color.cyan);
This is where the error accures and where i get the nullpointerexception everytime i type something in my jtextfield.
jtf.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (dos == null) {
if (jtf.getText().length() > 0) {
try {
dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(jtf.getText());
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
String[] empty = new String[]{""};
jl.setListData(empty);
}
}
}
}
);
jl.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (jl.getSelectedIndex() != -1) {
String item = (String) jl.getSelectedValue();
jl1.setText("");
for (String ingrediens : drinkar.get(item)) {
jl1.append(ingrediens + "\n");
}
}else{
jl1.setText("");
}
}
});
frame.add(jtf);
frame.add(jl);
frame.add(jl1);
frame.add(lab);
frame.add(lab1);
frame.add(lab2);
frame.add(js);
}
// tar emot arrayen, lagrar i ny array och visar i JList
public void getArrayList() {
String[] arr = null;
for(int i = 0; i < arr.length; i++){
arr = serverH.setList();
}
jl.setListData(arr);
}
public static void main(String[] args) {
GUI g = new GUI();
}
}
You define an instance variable »serverH«
but don’t assign any object to it. Therefore you should be facing the NullPointerException. You should assign an object to it, e.g.
This should solve your problem regarding the NullPointerException.