方法不在addactionlister中工作

时间:2016-05-23 18:22:13

标签: java actionlistener

我正在尝试构建一个LAN通信软件,其中进程应该是这样的,当用户登录时,客户端和服务器之间的网络应该启动。

我面临的问题是每当我在按钮的addactionlistener中放入我的startRunning()(这是启动网络的方法)方法时,整个软件会冻结,但如果我把方法放在addactionlistener之外的话开始很好。问题出现在btnNewButton.addActionListener中。如果计数为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 个答案:

答案 0 :(得分: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();
});