我的想法是创建一个包含多个按钮的小程序,点击每个按钮会显示不同的图像和背景。但是对于只有一个代码的代码,对于我提出的每个图像都会这样做很乏味。感谢您的投入......
package com.applet.image;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
public class AppletWithImage extends Applet implements ActionListener
{
private static final long serialVersionUID = 1L;
public static boolean clicked = false;
/*<applet code="AppletWithImage.class" width = "100" height = "100"></applet>*/
public void init()
{
Button b = new Button();
b.setLabel("Click Me");
b.setBounds(0, 0, 20, 20);
b.addActionListener(this);
add(b);
}
public void paint(Graphics g)
{
if(clicked==true)
{
Image i;
try {
URL base = new URL(getCodeBase().toString().substring(0, getCodeBase().toString().length()-4));
g.drawString(getCodeBase().toString().substring(0, getCodeBase().toString().length()-4), 10, 10);
MediaTracker mt = new MediaTracker(this);
i = getImage(base, "drawable/pic.PNG");
mt.addImage(i, 0);
g.drawImage(i, 20, 20, this);
}
catch (MalformedURLException e)
{
}
clicked = false;
}
}
@Override
public void actionPerformed(ActionEvent arg0)
{
clicked = true;
paint(this.getGraphics());
}
}