2016-05-23 88 views
0

我想建立一個局域網通信軟件,其中的過程應該是這樣的,當用戶登錄後,客戶端和服務器之間的網絡應該開始。方法不工作addactionlister

我面對的問題是,只要我把我的startRunning()(這是啓動網絡的方法)方法內的按鈕的addactionlistener整個軟件凍結,但如果我把方法之外的addactionlistener網絡開始很好。問題出在btnNewButton.addActionListener中。如果count是1,那麼它應該調用startrunning()方法,否則整個軟件都會凍結。

從startRunning()方法開始到下面的所有方法都能正常工作。數據庫還能夠檢查給定的用戶名和密碼是否正確。當startRunning方法在構造函數中但不在btnNewButton.addActionListener中時,此軟件運行良好。

 public class Server extends JFrame { 

private JTextField userText; 
private JTextArea chatWindow; 
private ObjectOutputStream output; 
private ObjectInputStream input; 
private ServerSocket server; 
private Socket connection; 

Connection dbconnection = null; 

private JTextField textField_1; 
private JPasswordField passwordField_1; 



public Server() { 

    super("Communication system"); 

    dbconnection = sqliteConnection.dbConnector(); 

    setupFrame(); 


} 

private void setupFrame() { 
    setBounds(100, 100, 450, 300); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    getContentPane().setLayout(null); 

    JLabel lblNewLabel = new JLabel("UserName"); 
    lblNewLabel.setBounds(10, 11, 81, 14); 
    getContentPane().add(lblNewLabel); 

    JLabel lblNewLabel_1 = new JLabel("Password"); 
    lblNewLabel_1.setBounds(10, 36, 59, 14); 
    getContentPane().add(lblNewLabel_1); 

    JButton btnNewButton = new JButton("Login"); 

    btnNewButton.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent arg0) { 

      try { 
       String query = "SELECT * FROM EmplyeeInfo WHERE Username=? and password=?"; 
       PreparedStatement pst = dbconnection 
         .prepareStatement(query); 

       pst.setString(1, textField_1.getText()); 
       pst.setString(2, passwordField_1.getText()); 

       ResultSet rs = pst.executeQuery(); 

       int count = 0; 
       while (rs.next()) { 
        count++; 
       } 
       if (count == 1) { 

        textField_1.setText(""); 
        passwordField_1.setText(""); 
        JOptionPane.showMessageDialog(null, 
          "Correct Username and Password"); 
        startRunning(); 

       } else { 
        textField_1.setText(""); 
        passwordField_1.setText(""); 
        JOptionPane.showMessageDialog(null, "Wrong try again"); 
       } 
       rs.close(); 
       pst.close(); 
      } catch (Exception e) { 
       // TODO: handle exception 
       JOptionPane.showMessageDialog(null, e); 
      } 
     } 
    }); 

    btnNewButton.setBounds(335, 7, 89, 23); 
    getContentPane().add(btnNewButton); 

    textField_1 = new JTextField(); 
    textField_1.setBounds(101, 8, 224, 20); 
    getContentPane().add(textField_1); 

    passwordField_1 = new JPasswordField(); 
    passwordField_1.setBounds(101, 33, 224, 20); 
    getContentPane().add(passwordField_1); 

    userText = new JTextField(); 
    userText.setBounds(10, 230, 330, 20); 
    userText.setEditable(false); 
    userText.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent event) { 
      // TODO Auto-generated method stub 
      sendMessage(event.getActionCommand()); 
      userText.setText(""); 
     } 
    }); 
    getContentPane().add(userText); 
    userText.setColumns(10); 

    chatWindow = new JTextArea(); 
    chatWindow.setBounds(10, 75, 330, 144); 
    getContentPane().add(chatWindow); 
    setVisible(true); 
} 

// set up and run the server 
public void startRunning() { 
    try { 
     server = new ServerSocket(6789, 100); 

     while (true) { 
      try { 
       waitForConnection(); 
       setupStreams(); 
       whileChatting(); 
      } catch (EOFException eofException) { 
       // TODO: handle exception 
       showMessage("\nServer Ended the conection!"); 
      } finally { 
       closeCrap(); 
      } 
     } 
    } catch (IOException ioException) { 
     ioException.printStackTrace(); 
    } 
} 

// wait for the connection, then display connection 

private void waitForConnection() throws IOException { 
    showMessage("Waiting for someone to connect... \n"); 
    connection = server.accept(); 
    showMessage(" Now connected to " 
      + connection.getInetAddress().getHostName()); 
} 

// get stream to send and receive data 
private void setupStreams() throws IOException { 
    output = new ObjectOutputStream(connection.getOutputStream()); 
    output.flush(); 
    input = new ObjectInputStream(connection.getInputStream()); 
    showMessage("\n Streams are now Setup \n"); 
} 

// during the chat conversation 
private void whileChatting() throws IOException { 
    String message = " You are now connected"; 
    sendMessage(message); 
    ableToType(true); 

    do { 
     // have a conversation 
     try { 
      message = (String) input.readObject(); 
      showMessage("\n" + message); 
     } catch (ClassNotFoundException classNotFoundException) { 
      showMessage("\n I don't know what the user send"); 
     } 

    } while (!message.equals("CLIENT - END")); 
} 

// closing the streams and sockets after done chatting 
private void closeCrap() { 
    showMessage("\n closing connections...\n"); 
    ableToType(false); 
    try { 
     output.close(); 
     input.close(); 
     connection.close(); 
    } catch (IOException ioException) { 
     ioException.printStackTrace(); 
    } 
} 

// send message to a client 
private void sendMessage(String message) { 
    try { 
     output.writeObject("SERVER - " + message); 
     output.flush(); 
     showMessage("\nSERVER -" + message); 
    } catch (IOException ioException) { 
     chatWindow.append("\n Error : can't send the message"); 
    } 
} 

// updates chat window 

private void showMessage(final String text) { 
    SwingUtilities.invokeLater(new Runnable() { 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      chatWindow.append("" + text); 
     } 
    }); 
} 

// allowing user to type stuff in the box 

private void ableToType(final boolean tof) { 
    SwingUtilities.invokeLater(new Runnable() { 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      userText.setEditable(tof); 
     } 
    }); 
} 

}

回答

1

您可能必須把它放在一個不同的線程 - 你可以本地化線程只包括startRunning方法或你想要什麼:

public void actionPerformed(ActionEvent arg0) { 

    Thread th=new Thread() { 
     public void run() { 
     try { 
      String query = "SELECT * FROM EmplyeeInfo WHERE Username=? and password=?"; 
      PreparedStatement pst = dbconnection 
        .prepareStatement(query); 

      pst.setString(1, textField_1.getText()); 
      pst.setString(2, passwordField_1.getText()); 

      ResultSet rs = pst.executeQuery(); 

      int count = 0; 
      while (rs.next()) { 
       count++; 
      } 
      if (count == 1) { 

       textField_1.setText(""); 
       passwordField_1.setText(""); 
       JOptionPane.showMessageDialog(null, 
         "Correct Username and Password"); 
       startRunning(); 

      } else { 
       textField_1.setText(""); 
       passwordField_1.setText(""); 
       JOptionPane.showMessageDialog(null, "Wrong try again"); 
      } 
      rs.close(); 
      pst.close(); 
     } catch (Exception e) { 
      // TODO: handle exception 
      JOptionPane.showMessageDialog(null, e); 
     } 
    } 
    }; 
    th.start(); 
}); 
+0

謝謝它解決了我的問題 – Saud

+0

你能告訴我爲什麼我需要新的線程,爲什麼我的軟件在我沒有線程的情況下啓動startrunning()方法時會凍結? – Saud