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.