2014-05-28 3 views
1

У меня есть клиент и сервер. Сервер отправляет Клиенту несколько вопросов. На стороне клиента я хочу отобразить эти вопросы в окне приложения SWT.SWT NullPointerException

Я использую один поток, чтобы показать контакты окна и основного потока с Сервером. После того, как клиент получает вопросы, NullPointerException бросается в текстовый виджет. (метод writeQuestions ниже). Я думаю, что «q1Txt» не является нулевым, потому что он инициируется методом «createContets». Кроме того, аррайалист, у которого есть вопрос, тоже не является нулевым, потому что я его проверил.

Вы можете мне помочь?

Мой код ниже.

public class Client { 

protected static Shell shell; 
private static Text q1txt; 
private static Text q2txt; 
private static Text q3txt; 
private static Text q4txt; 
private static Text q5txt; 
private static Text ans1txt; 
private static Text ans2txt; 
private static Text ans3txt; 
private static Button ans5YesBtn; 
private static Button ans4NoBtn; 
private static Button ans4YesBtn; 
private static Button ans5NoBtn; 
private static ArrayList<Integer> ansList = new ArrayList<Integer>(); 
private static boolean isAnswered = false; 
static String name; 
static int socketNum; 
static Socket socket; 
public static int l = 4; 


public static void main(String[] args) throws InterruptedException { 

    new Screen().start(); 

    try { 
     socket = new Socket("", 9898); 
     ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream()); 
     ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream()); 
     objOut.writeObject("8080"); 

     ArrayList<String> questions = (ArrayList<String>) objIn.readObject(); 

     writeQuestions(questions); 
     while(!isAnswered) 
      Thread.sleep(2000); 

     socket.close(); 
    } catch (UnknownHostException e) { 
     System.err.println("There is not like this company!"); 
    } catch (IOException e) { 
     System.err.println("Company does not answer!"); 
    } catch (ClassNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 


public static void writeQuestions(ArrayList<String> questions){ 
    q1txt.setText(questions.get(0)); // The exception point is here 
    q2txt.setText(questions.get(1)); 
    q3txt.setText(questions.get(2)); 
    q4txt.setText(questions.get(3)); 
    q5txt.setText(questions.get(4)); 
} 

private static class Screen extends Thread { 
    public void run() { 
     open();  
    } 

} 


public static void open(){ 
    Display display = Display.getDefault(); 
    createContents(); 
    shell.open(); 
    shell.layout(); 
    while (!shell.isDisposed()) { 
     if (!display.readAndDispatch()) { 
      display.sleep(); 
     } 

    } 
} 


protected static void createContents() { 
    shell = new Shell(); 
    shell.setSize(499, 369); 
    shell.setText("SWT Application"); 
    shell.setLayout(null); 

    Composite questionsComp = new Composite(shell, SWT.NONE); 
    questionsComp.setBounds(10, 10, 373, 298); 

    q1txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY); 
    q1txt.setBounds(0, 0, 259, 21); 

    q2txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY); 
    q2txt.setBounds(0, 51, 259, 21); 

    q3txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY); 
    q3txt.setBounds(0, 95, 259, 21); 
    q4txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY); 
    q4txt.setBounds(0, 140, 259, 21); 

    q5txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY); 
    q5txt.setBounds(0, 189, 259, 21); 

    ans1txt = new Text(questionsComp, SWT.BORDER); 
    ans1txt.setBounds(272, 0, 58, 21); 

    ans2txt = new Text(questionsComp, SWT.BORDER); 
    ans2txt.setBounds(272, 51, 58, 21); 

    ans3txt = new Text(questionsComp, SWT.BORDER); 
    ans3txt.setBounds(272, 95, 58, 21); 

    Group ans4group = new Group(questionsComp, SWT.NONE); 
    ans4group.setBounds(265, 121, 97, 47); 
    ans4group.setLayout(null); 

    ans4YesBtn = new Button(ans4group, SWT.RADIO); 
    ans4YesBtn.setBounds(10, 20, 39, 16); 
    ans4YesBtn.addSelectionListener(new SelectionAdapter() { 
     @Override 
     public void widgetSelected(SelectionEvent e) { 
     } 
    }); 
    ans4YesBtn.setText("Yes"); 

    ans4NoBtn = new Button(ans4group, SWT.RADIO); 
    ans4NoBtn.setBounds(55, 20, 39, 16); 
    ans4NoBtn.addSelectionListener(new SelectionAdapter() { 
     @Override 
     public void widgetSelected(SelectionEvent e) { 
     } 
    }); 
    ans4NoBtn.setText("No"); 

    Group ans5Group = new Group(questionsComp, SWT.NONE); 
    ans5Group.setBounds(265, 176, 97, 47); 

    ans5NoBtn = new Button(ans5Group, SWT.RADIO); 
    ans5NoBtn.setBounds(55, 21, 39, 16); 
    ans5NoBtn.setText("No"); 

    ans5YesBtn = new Button(ans5Group, SWT.RADIO); 
    ans5YesBtn.setBounds(10, 21, 39, 16); 
    ans5YesBtn.setText("Yes"); 

    Button btnGainCalculation = new Button(questionsComp, SWT.NONE); 
    btnGainCalculation.addSelectionListener(new SelectionAdapter() { 
     @Override 
     public void widgetSelected(SelectionEvent e) { 
      //controls all answers 
      if(ans1txt.getText().equals("") || ans2txt.getText().equals("") || ans3txt.getText().equals("")){ 
       MessageDialog.openWarning(shell, "Warning", "Please answer all questions."); 
      }else if((!ans4NoBtn.getSelection() && !ans4YesBtn.getSelection()) || (!ans5NoBtn.getSelection() && !ans5YesBtn.getSelection())){ 
       MessageDialog.openWarning(shell, "Warning", "Please answer all questions."); 
      }else if(!isNumeric(ans1txt.getText()) || !isNumeric(ans2txt.getText()) || !isNumeric(ans3txt.getText())){ 
       MessageDialog.openWarning(shell, "Warning", "Please answer correctly."); 
      }else 
       isAnswered = true; 

     } 
    } 
      ); 
    btnGainCalculation.setBounds(0, 236, 97, 25); 
    btnGainCalculation.setText("Gain Calculation"); 

} 
public static boolean isNumeric(String str) 
{ 
    return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. 
} 

}

+1

Ну, Aparently ваш ответ поступает до 'q1txt' на самом деле создается. Всегда отправляйте трассировку стека. Кроме того, вы можете просто проверить, что именно «null», отлаживая ваш код или добавляя сообщения журнала. – Baz

+1

Да, вы правы, ответ приходит раньше. Перед подключением к серверу я добавляю sleep(), и теперь он работает. Благодаря! – user1914367

ответ

0

Я уверен, что проблема заключается в дальнейшем исполнение для "createContent". Мы должны убедиться, что компонент будет использовать после создания

Попробуйте это:

import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import java.util.ArrayList; 

import org.eclipse.jface.dialogs.MessageDialog; 
import org.eclipse.swt.SWT; 
import org.eclipse.swt.events.SelectionAdapter; 
import org.eclipse.swt.events.SelectionEvent; 
import org.eclipse.swt.widgets.Button; 
import org.eclipse.swt.widgets.Composite; 
import org.eclipse.swt.widgets.Display; 
import org.eclipse.swt.widgets.Group; 
import org.eclipse.swt.widgets.Shell; 
import org.eclipse.swt.widgets.Text; 

public class Client{ 
    protected static Shell    shell; 
    private static Text     q1txt; 
    private static Text     q2txt; 
    private static Text     q3txt; 
    private static Text     q4txt; 
    private static Text     q5txt; 
    private static Text     ans1txt; 
    private static Text     ans2txt; 
    private static Text     ans3txt; 
    private static Button    ans5YesBtn; 
    private static Button    ans4NoBtn; 
    private static Button    ans4YesBtn; 
    private static Button    ans5NoBtn; 
    private static ArrayList<Integer> ansList  = new ArrayList<Integer>(); 
    private static boolean    isAnswered = false; 
    static String      name; 
    static int       socketNum; 
    static Socket      socket; 
    public static int     l   = 4; 

    public static void main(String[] args) throws InterruptedException { 
     Screen screen = new Screen(); 
     screen.setCreationComplete(new CreationCompleteAction()); 
    } 


    private static class Screen extends Thread { 
     Runnable creationCompleteAction; 

     public void setCreationComplete(Runnable action){ 
      this.creationCompleteAction = action; 
     } 

     public void run() { 
      Display display = Display.getDefault(); 
      createContents(); 

      if(creationCompleteAction != null){ 
       creationCompleteAction.run(); 
      } 

      shell.open(); 
      shell.layout(); 
      while (!shell.isDisposed()) { 
       if (!display.readAndDispatch()) { 
        display.sleep(); 
       } 

      } 
     } 

    } 

    public static class CreationCompleteAction implements Runnable { 
     @Override 
     public void run() { 
      try { 
       socket = new Socket("", 9898); 
       ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream()); 
       ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream()); 
       objOut.writeObject("8080"); 

       ArrayList<String> questions = (ArrayList<String>) objIn.readObject(); 

       writeQuestions(questions); 
       while (!isAnswered) 
        Thread.sleep(2000); 

       socket.close(); 
      } catch (UnknownHostException e) { 
       System.err.println("There is not like this company!"); 
      } catch (IOException e) { 
       System.err.println("Company does not answer!"); 
      } catch (ClassNotFoundException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 

    public static void writeQuestions(ArrayList<String> questions) { 
     q1txt.setText(questions.get(0)); // The exception point is here 
     q2txt.setText(questions.get(1)); 
     q3txt.setText(questions.get(2)); 
     q4txt.setText(questions.get(3)); 
     q5txt.setText(questions.get(4)); 
    } 

    private static class Screen extends Thread { 
     public void run() { 
      Display display = Display.getDefault(); 
      createContents(); 
      shell.open(); 
      shell.layout(); 
      while (!shell.isDisposed()) { 
       if (!display.readAndDispatch()) { 
        display.sleep(); 
       } 

      } 
     } 

    } 

    protected static void createContents() { 
     shell = new Shell(); 
     shell.setSize(499, 369); 
     shell.setText("SWT Application"); 
     shell.setLayout(null); 

     Composite questionsComp = new Composite(shell, SWT.NONE); 
     questionsComp.setBounds(10, 10, 373, 298); 

     q1txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY); 
     q1txt.setBounds(0, 0, 259, 21); 

     q2txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY); 
     q2txt.setBounds(0, 51, 259, 21); 

     q3txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY); 
     q3txt.setBounds(0, 95, 259, 21); 
     q4txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY); 
     q4txt.setBounds(0, 140, 259, 21); 

     q5txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY); 
     q5txt.setBounds(0, 189, 259, 21); 

     ans1txt = new Text(questionsComp, SWT.BORDER); 
     ans1txt.setBounds(272, 0, 58, 21); 

     ans2txt = new Text(questionsComp, SWT.BORDER); 
     ans2txt.setBounds(272, 51, 58, 21); 

     ans3txt = new Text(questionsComp, SWT.BORDER); 
     ans3txt.setBounds(272, 95, 58, 21); 

     Group ans4group = new Group(questionsComp, SWT.NONE); 
     ans4group.setBounds(265, 121, 97, 47); 
     ans4group.setLayout(null); 

     ans4YesBtn = new Button(ans4group, SWT.RADIO); 
     ans4YesBtn.setBounds(10, 20, 39, 16); 
     ans4YesBtn.addSelectionListener(new SelectionAdapter() { 
      @Override 
      public void widgetSelected(SelectionEvent e) { 
      } 
     }); 
     ans4YesBtn.setText("Yes"); 

     ans4NoBtn = new Button(ans4group, SWT.RADIO); 
     ans4NoBtn.setBounds(55, 20, 39, 16); 
     ans4NoBtn.addSelectionListener(new SelectionAdapter() { 
      @Override 
      public void widgetSelected(SelectionEvent e) { 
      } 
     }); 
     ans4NoBtn.setText("No"); 

     Group ans5Group = new Group(questionsComp, SWT.NONE); 
     ans5Group.setBounds(265, 176, 97, 47); 

     ans5NoBtn = new Button(ans5Group, SWT.RADIO); 
     ans5NoBtn.setBounds(55, 21, 39, 16); 
     ans5NoBtn.setText("No"); 

     ans5YesBtn = new Button(ans5Group, SWT.RADIO); 
     ans5YesBtn.setBounds(10, 21, 39, 16); 
     ans5YesBtn.setText("Yes"); 

     Button btnGainCalculation = new Button(questionsComp, SWT.NONE); 
     btnGainCalculation.addSelectionListener(new SelectionAdapter() { 
      @Override 
      public void widgetSelected(SelectionEvent e) { 
       //controls all answers 
       if (ans1txt.getText().equals("") || ans2txt.getText().equals("") || ans3txt.getText().equals("")) { 
        MessageDialog.openWarning(shell, "Warning", "Please answer all questions."); 
       } else if ((!ans4NoBtn.getSelection() && !ans4YesBtn.getSelection()) || (!ans5NoBtn.getSelection() && !ans5YesBtn.getSelection())) { 
        MessageDialog.openWarning(shell, "Warning", "Please answer all questions."); 
       } else if (!isNumeric(ans1txt.getText()) || !isNumeric(ans2txt.getText()) || !isNumeric(ans3txt.getText())) { 
        MessageDialog.openWarning(shell, "Warning", "Please answer correctly."); 
       } else 
        isAnswered = true; 

      } 
     }); 
     btnGainCalculation.setBounds(0, 236, 97, 25); 
     btnGainCalculation.setText("Gain Calculation"); 

    } 

    public static boolean isNumeric(String str) { 
     return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. 
    } 
} 
Смежные вопросы