sender.java

来自「java的书上例子」· Java 代码 · 共 91 行

JAVA
91
字号
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Enumeration;
import Receiver;
import javax.swing.*;

/** 该小应用程序可以向指定名称的同页的小应用程序发送消息,
  * 接受消息的小应用程序名在HTML文件中用参数receiverName指定,
  * 可以在程序中用getParameter("receiverName")得到该名称,
  * 通过得到的Applet名调用对方的接受消息的方法(该例中为
  * processRequestFrom(String senderName)方法),即可向对方发送消息 */

/** JApplet类 */
public class Sender extends JApplet implements ActionListener
{
	private String myName;
	private TextField nameField;
	private TextArea status;
	private String newline;
	
	/** init()方法 */
	public void init()
	{
		Container contentPane=getContentPane();
		
		GridBagLayout gridBag=new GridBagLayout();
		GridBagConstraints c=new GridBagConstraints();
		contentPane.setLayout(gridBag);
		Label receiverLabel=new Label("Receiver name:",Label.RIGHT);
		gridBag.setConstraints(receiverLabel,c);
		contentPane.add(receiverLabel);
		
		nameField=new TextField(getParameter("receiverName"),10);
		c.fill=GridBagConstraints.HORIZONTAL;
		gridBag.setConstraints(nameField,c);
		contentPane.add(nameField);
		nameField.addActionListener(this);
		
		Button button=new Button("Send message");
		c.gridwidth=GridBagConstraints.REMAINDER;
		c.anchor=GridBagConstraints.WEST;
		c.fill=GridBagConstraints.NONE;
		gridBag.setConstraints(button,c);
		contentPane.add(button);
		button.addActionListener(this);
		
		status=new TextArea(5,60);
		status.setEditable(false);
		c.anchor=GridBagConstraints.CENTER;
		c.fill=GridBagConstraints.BOTH;
		c.weightx=1.0;
		c.weighty=1.0;
		gridBag.setConstraints(status,c);
		contentPane.add(status);
		
		myName=getParameter("name");
		Label senderLabel=new Label("(My name is "+myName+".)",Label.CENTER);
		c.weightx=0.0;
		c.weighty=0.0;
		gridBag.setConstraints(senderLabel,c);
		contentPane.add(senderLabel);
		
		newline=System.getProperty("line.separator");
	}//init()方法结束
	
	/** 动作事件处理方法 */
	public void actionPerformed(ActionEvent e)
	{
		Applet receiver=null;
		String receiverName=nameField.getText();
		receiver=getAppletContext().getApplet(receiverName);
		if(receiver!=null)
			if(!(receiver instanceof Receiver))
				status.append("found applet named "+receiverName+","+"but it's not a Receiver object"+newline);
			else
			{
				status.append("Found applet named "+receiverName+newline+"   sending message to it."+newline);
				((Receiver)receiver).processRequestFrom(myName);
			}
		else
			status.append("Couldn't find any applet named "+receiverName+"."+newline);
	}//actionPerformed()方法结束
	
	/** JApplet类的paint()方法 */
	public void paint(Graphics g)
	{
		g.drawRect(0,0,getSize().width-1,getSize().height-1);
	}//paint()方法结束
}//Sender类结束

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?