我试图通过在Java中开发一个简单的绘图应用程序来进入Swing。
问题是我使用Points
数组来跟踪mouseDragged
事件,但是当我释放鼠标按钮并开始绘制新行时,他们会得到已连接(前一行'最后一个节点到新行的第一个点)。
我想也许要跟踪另一个Points
中mousePressed
和mouseReleased
听众所听取的ArrayList
,知道哪些是开始和结束点。每一行然后,当它在点之间绘制线条时,检查它们是否在ArrayList
中并避免绘制该线。
您建议的方法是什么?如何在我的代码中实现这一点?谢谢!
package ccdraw;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.event.MouseInputListener;
@SuppressWarnings("serial")
public class DrawingArea extends JPanel implements MouseInputListener {
private ArrayList<Point> pointList = new ArrayList<Point>();
//private ArrayList<Point> beginEndPoints = new ArrayList<Point>();
public DrawingArea() {
super();
super.setPreferredSize(new Dimension(400,400));
setBorder(BorderFactory.createLineBorder(Color.black));
addMouseListener(this);
addMouseMotionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.setStroke(new BasicStroke(1.5f));
for (int i=1;i<pointList.size()-1;i++){
// here i should check when it changes between old and new line
// and don't draw the line between those two points!
//if(pointList.get(i).x - pointList.get(i+1).x <= 1 && pointList.get(i).y - pointList.get(i+1).y <= 1)
g2d.drawLine(pointList.get(i).x, pointList.get(i).y, pointList.get(i+1).x, pointList.get(i+1).y);
}
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
pointList.add(arg0.getPoint());
}
@Override
public void mouseReleased( MouseEvent arg0) {
pointList.add(arg0.getPoint());
repaint();
}
@Override
public void mouseDragged(MouseEvent arg0) {
pointList.add(arg0.getPoint());
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:2)
我想也许可以跟踪另一个arraylist中mousePressed和mouseReleased侦听器监听的Points,
保留ArrayLists的ArrayList。
因此,每次执行mousePressed时,都会为mouseDragged事件添加的一系列Points启动一个新的ArrayList。
然后在绘画代码中迭代两个ArrayLists。这应该比为起点/终点添加异常逻辑更容易。
另一种选择是直接绘制到BufferedImage,因此您根本不需要跟踪点。查看Custom Painting Approaches,比较这两种一般的自定义绘画方法,以确定哪种方法最适合您的要求。