所以我一直在努力学习挥杆并尝试制作绘画程序。
我一直遇到的问题是,如果你将鼠标移动到快速,它就不会填补空白(如果你不打开则运行代码)
我认为这可能是它填补了arraylist的地方。
所以我想知道如何解决这个问题,谢谢!
我的代码:
import javax.swing.*;
import java.util.ArrayList;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseAdapter;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Window extends JPanel implements MouseListener{
//new array list
private ArrayList<Point> dots;
static JFrame frame;
Font f;
static int Dx1=0, Dx2=0, Dy1=0, Dy2=0; //fill void dots
static int v=0;
static int posX = 250;
static int posY = 250;
static double winX=0;
static double winY=0;
public Window() {
dots = new ArrayList<Point>();
frame = new JFrame();
f = new Font("Calibri", Font.BOLD, 30);
this.setBackground(Color.white);
frame.add(this);
frame.setResizable(true);
frame.setVisible(true);
frame.setSize(500, 500);
frame.setTitle("Minigameshuehu");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
// MOVE BALL DEPENDING ON "Dragging"
this.addMouseListener(this);
this.addMouseListener(new MouseAdapter() {
});
this.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
dots.add(new Point(e.getX(), e.getY())); // adding pos to to array to make dots
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
posX = e.getX() - 3;
posY = e.getY() - 3;
repaint();
}
}
);
//End of moving ball
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(new Color(0,0,0));
g2.fillOval(posX, posY, 6, 6);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.black);
for (Point point : dots) {
g2.fillOval(point.x-3, point.y-3, 6, 6);
}
}
public static void main(String[] args) throws InterruptedException {
Window applikation = new Window();
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// posX=(e.getX()-25);
// posY=(e.getY()-25);
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
v=0;
// TODO Auto-generated method stub
}
}
答案 0 :(得分:2)
如果你将鼠标移动到快速,它就不会填补空白
这是正确的,不会为每个像素生成MouseEvent,因此您无法为生成的每个点绘制一个椭圆。
相反,您需要在ArrayList中的两个点之间绘制一条线。
for (int i = 0; i < dots.size() - 1; i++)
{
Point p1 = dots.get(i);
Point p2 = dots.get(i + 1);
g2.drawLine(...);
}
您还需要使用以下内容更改绘制的线条的大小:
g2.setStroke(new BasicStroke(15, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
这将绘制一条带有圆边的线条,使其看起来像椭圆形的末端。