我想在鼠標拖動時在JPanel上繪製2(或更多)行。當我在我的代碼使用super.paintComponent(g)
,我不能得出2號線在面板上,但是當我不使用super.paintComponent(g)
;,其結果是醜陋的,如下面的圖:拖動鼠標時在Jpanel上繪製線條
我明白爲什麼這些線的行爲如此。
如何在拖動鼠標時在Jpanel上繪製線條? 順便說一句,通過g2d.draw(line2d)
繪製的線有時它不是平滑線(下面圖)
我的代碼到目前爲止:
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class LineDrawing extends JPanel implements MouseMotionListener, MouseListener{
Point point1;
Point point2;
Line2D line2d;
public LineDrawing(){
super();
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
public void paintComponent(Graphics g){
//super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if(point1!=null && point2!=null){
g2d.setPaint(Color.RED);
g2d.setStroke(new BasicStroke(1.5f));
g2d.draw(line2d);
}
}
@Override
public void mouseDragged(MouseEvent e) {
point2 = e.getPoint();
line2d = new Line2D.Double(point1, point2);
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
point1 = e.getPoint();
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public static void main(String a[]){
EventQueue.invokeLater(new Runnable(){
@Override
public void run() {
JFrame frame = new JFrame();
LineDrawing linedraw= new LineDrawing();
frame.add(linedraw);
frame.setSize(500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
你說得對,他們消失了。什麼原因? – 2012-04-18 13:43:32
謝謝。順便說一句,paintComponent繪製的線 - 有時不是平滑線。我怎樣才能擺脫這一點? – 2012-04-18 14:24:25
我編輯了這個問題,所以你可以在圖片上看到 - 這條線不是直線。我的意思是一些線條,而不是全部線條。 – 2012-04-18 14:34:58