1
我想帶回那是以前問了一個問題:java draw line as the mouse is moved用鼠標點擊和拖動的Java Swing畫線
「我想一個功能添加到我的應用程序,允許用戶通過繪製一條直線在開始位置點擊鼠標並在結束位置釋放它,線條應該隨着鼠標的移動而移動,直到它最終被釋放爲止;類似於使用Microsoft Paint應用程序可以繪製的線條的方式
可以實現這一點,以便線條在移動時重新繪製,而不重繪其他可能已經繪製在該矩形區域中的東西?「
問題是:我如何繪製多條線,舊線仍在那裏?
這是對我的作品的代碼,但前行獲取在繪製一個新的儘快抹去:
public static void main(String args[]) throws Exception {
JFrame f = new JFrame("Draw a Red Line");
f.setSize(300, 300);
f.setLocation(300, 300);
f.setResizable(false);
JPanel p = new JPanel() {
Point pointStart = null;
Point pointEnd = null;
{
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointStart = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
pointStart = null;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
pointEnd = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
pointEnd = e.getPoint();
repaint();
}
});
}
public void paint(Graphics g) {
super.paint(g);
if (pointStart != null) {
g.setColor(Color.RED);
g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}
}
};
f.add(p);
f.setVisible(true);
}
謝謝你。你能夠提供代碼或幫助我使用我的代碼嗎?我不是一個很好的程序員。我嘗試了第一種方法,但不確定是否應該有Shape或Point的ArrayList(看到它們有pointStart和pointEnd)。我試了兩次,但都失敗了。 – Reens
@Reens,我的確幫你編寫了代碼。我給了你兩個實例。修改工作示例以繪製一條線而不是一個矩形。 – camickr