我想知道是否可以在小程序上绘制线条。
你当然可以。只需在小程序中放置一个面板,添加一个鼠标运动侦听器并根据事件在该面板上绘图。
说明这一点的小例子
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<Point> points = new ArrayList<Point>();
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();
}
}
}
注意:使用缓冲图像而不是存储点可能在很长一段时间内更具可扩展性(否则点列表可能会变得巨大),但需要注意面板尺寸的增加。