小白求助!请问怎么用Graphics类画多边形??要用drawLine 这个方法!
具体是这样:先自己画一条线,再在其他地方单击,使其自动生成一条(和前一条线的释放点连在一起的)线,如此重复,最后双击,形成闭合多边形。救救孩子吧,要交作业了!!!
能给一个程序最好了!!
2018-11-12 14:19
2018-11-18 19:25
程序代码:
public class Test extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
static class Cell {
int x;
int y;
public int getX() {
return x;
}
public int getY() {
return y;
}
public Cell(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
private static List<Cell> cells = new ArrayList<>();
@Override
public void paint(Graphics g) {
g.setColor(Color.RED);
int[] xPoints = new int[cells.size()];
int[] yPoints = new int[cells.size()];
for (int i = 0; i < cells.size(); i++) {
xPoints[i] = cells.get(i).getX();
yPoints[i] = cells.get(i).getY();
}
g.fillPolygon(xPoints, yPoints, cells.size());
if(cells.size() < 1) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, 400, 400);
}
}
static LocalDateTime prevClickTime = LocalDateTime.now();
static LocalDateTime curClickTime = null;
MouseAdapter mouseAdapter = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Test.this.repaint();
curClickTime = LocalDateTime.now();
cells.add(new Cell(e.getX()-8, e.getY()-30));
Duration duration = Duration.between(prevClickTime, curClickTime);
int nano = duration.getNano();
if(nano <= Duration.ofMillis(180).getNano()) {
System.out.println("clear");
cells.clear();
}
prevClickTime = curClickTime;
};
};
private void start() {
JFrame jframe = new JFrame();
jframe.setVisible(true);
jframe.setSize(400, 400);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.add(this);
jframe.addMouseListener(mouseAdapter);
}
public static void main(String[] args) {
new Test().start();
}
}

2018-11-19 23:15