单击JButton时不会发生相应的事件

package ServerAndClient;

import javax.swing.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;

public class Server  extends JFrame implements ActionListener
{
	private JTextArea textareareceiveorsend;
	private JTextField textfieldtosend;
	private String texttosend=null;
	private JButton sendbutton;
	private ServerSocket server;
	private Socket client;
	
	public Server()
	{
		super("Server");
		JPanel panel=new JPanel();
		setContentPane(panel);
		
		panel.setLayout(null);
		
		textareareceiveorsend=new JTextArea(">>wait for connection\r\n");
		textareareceiveorsend.setLineWrap(true);
		textareareceiveorsend.setBounds(0,0, 500,300);
		panel.add(textareareceiveorsend);
		
		textfieldtosend=new JTextField();
		textfieldtosend.setBounds(50,320,400, 30);
		panel.add(textfieldtosend);
		
		sendbutton=new JButton("发送");
		sendbutton.setBounds(215,400,70, 30);
		panel.add(sendbutton);

		this.setSize(500,500);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);

		waitForConnection();
		writeTextInTextarea();
		<pre name="code" class="java">		sendbutton.addActionListener(this);
}public void waitForConnection(){final int PORT=4040;try {server=new ServerSocket(PORT);client=server.accept();textareareceiveorsend.append("connect with"+client.getLocalAddress()+"\r\n");}catch (IOException e) {e.printStackTrace();}}public void writeTextInTextarea(){try{BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));while(true){String text=in.readLine();if(text.equals("byebye")){textareareceiveorsend.append(text+"\r\n");break;}else{textareareceiveorsend.append("<<"+text+"\r\n");}}}catch(IOException e){e.printStackTrace();}}public void actionPerformed(ActionEvent e){texttosend=textfieldtosend.getText();textareareceiveorsend.append(">>"+texttosend+"\r\n");textfieldtosend.setText("");PrintWriter out;try {out = new PrintWriter(client.getOutputStream(),true);out.println(texttosend);} catch (IOException e1) {// TODO 自动生成的 catch 块e1.printStackTrace();}}}

如上面那段服务器端代码所示,在addActionListener前面还有两个方法,会造成点击JButton没有反应的情况,其实仔细想一想就能明白原因,在那两个方法中有相关的语句是从客户端中读取客户端发送来的信息,如果客户端一直不发送来信息,那么线程就会阻塞在那里,当然点击方法后面的JButton就不会有任何反应,解决方案就是将addActionListener放在这两个方法的前面。建议初始化完一个按钮后就立刻添加addActionListener,不要在这中间在穿插其他语句。
          
展开阅读全文

没有更多推荐了,返回首页