java中Applet怎么擦除,使用油漆或重新绘制方法来画在一个applet JAVA线

I am wondering if it's possible to paint lines over an applet. I am loading the applet from an external source, but I'd like to paint lines where the cursor is on the screen.

Can someone tell me how I'd do this please?

Here's an example.

g.drawLine(mouse.getLocation().x - 6, mouse.getLocation().y,

mouse.getLocation().x + 6, mouse.getLocation().y);

g.drawLine(mouse.getLocation

().x, mouse.getLocation().y - 6,

mouse.getLocation().x, mouse.getLocation().y + 6);

解决方案

I am wondering if it's possible to paint lines over an applet.

Sure you can. Simply put a panel in the applet, add a mouse motion listener and draw on that panel according to the events.

Small example illustrating this

import java.awt.Color;

import java.awt.Dimension;

import java.awt.Point;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.lang.reflect.InvocationTargetException;

import java.util.ArrayList;

import java.util.List;

import javax.swing.JApplet;

import javax.swing.JPanel;

import javax.swing.SwingUtilities;

public class TestAppletDraw extends JApplet {

public static class MyDrawPanel extends JPanel {

private List points = new ArrayList();

public MyDrawPanel() {

setBackground(Color.WHITE);

MouseAdapter listener = new MouseAdapter() {

@Override

public void mouseClicked(MouseEvent e) {

points.clear();

repaint();

}

@Override

public void mouseMoved(MouseEvent e) {

points.add(e.getPoint());

repaint();

}

};

addMouseListener(listener);

addMouseMotionListener(listener);

}

@Override

public Dimension getPreferredSize() {

return new Dimension(300, 300);

}

@Override

protected void paintComponent(java.awt.Graphics g) {

super.paintComponent(g);

Point p1 = null;

Point p2 = null;

g.setColor(Color.BLUE);

for (Point p : points) {

p2 = p1;

p1 = p;

if (p1 != null && p2 != null) {

g.drawLine(p1.x, p1.y, p2.x, p2.y);

}

}

}

}

protected void initUI() {

add(new MyDrawPanel());

validate();

}

@Override

public void init() {

super.init();

try {

SwingUtilities.invokeAndWait(new Runnable() {

@Override

public void run() {

initUI();

}

});

} catch (InvocationTargetException e) {

e.printStackTrace();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

NB: Using a buffered image instead of storing points may be more scalable over long periods of time (otherwise the points List can become gigantic) but it requires to take care of panel size increases.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值