📄 graphapplet.java
字号:
import java.awt.*;
class GraphApplet extends Frame {
GraphApplet() {
super("Rectangle Example");
add("Center", new ImageCanvas());
setSize(200, 200);
show();
}
public static void main(String[] args) {
new GraphApplet();
}
}
class ImageCanvas extends Canvas {
int numCoins = 3;
Rectangle[] coins = new Rectangle[numCoins];
Rectangle[] slots = new Rectangle[numCoins];
Color[] colors = {Color.red, Color.green, Color.blue};
Image bbuf;
Graphics bbufG;
ImageCanvas() {
for (int i=0; i<numCoins; i++) {
coins[i] = new Rectangle(rand(50), rand(50), 50, 50);
slots[i] = new Rectangle();
}
}
int rand(int r) {
return (int)Math.floor(Math.random()*r);
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
int w = getSize().width;
int h = getSize().height;
if (bbuf == null
|| w > bbuf.getWidth(null)
|| h > bbuf.getHeight(null)) {
bbuf = createImage(w, h);
bbufG = bbuf.getGraphics();
}
bbufG.setColor(Color.white);
bbufG.fillRect(0, 0, getSize().width, getSize().height);
// paint slots
for (int i=0; i<numCoins; i++) {
slots[i].setBounds(i*w/3, h-30, w/3, 30);
slots[i].grow(-5, -2);
bbufG.setColor(colors[i]);
bbufG.fillRect(slots[i].x, slots[i].y,
slots[i].width, slots[i].height);
}
// paint coins
for (int i=0; i<numCoins; i++) {
if (!coins[i].isEmpty()) {
if (dragging == i && coins[i].intersects(slots[i])) {
bbufG.setColor(Color.black);
} else {
bbufG.setColor(colors[i]);
}
bbufG.fillOval(coins[i].x, coins[i].y,
coins[i].width, coins[i].height);
}
}
g.drawImage(bbuf, 0, 0, this);
}
int dragging = -1;
Point offset;
public synchronized boolean mouseDown(Event evt, int x, int y) {
for (int i=coins.length-1; i>=0; i--) {
if (!coins[i].isEmpty() && coins[i].contains(x, y)) {
dragging = i;
offset = new Point(coins[i].x-x, coins[i].y-y);
return true;
}
}
return false;
}
public synchronized boolean mouseDrag(Event evt, int x, int y) {
if (dragging >= 0) {
coins[dragging].setLocation(x, y);
coins[dragging].translate(offset.x, offset.y);
repaint();
return true;
}
return false;
}
public synchronized boolean mouseUp(Event evt, int x, int y) {
if (dragging >= 0) {
if (coins[dragging].intersects(slots[dragging])) {
coins[dragging].width = 0; // make it empty
dragging = -1;
}
repaint();
return true;
}
return false;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -