尝试在awt画布上用鼠标绘制图形(现在是一条线)。我第一次尝试java图形。所以不确定如何去做。这是我的第一次尝试:
package def.grafi;
import java.awt.Canvas;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Dra {
Frame f = new Frame();
public void disp() {
f.setBounds(100, 100, 200, 200);
MosL ml = new MosL();
Can c = new Can();
f.add(c);
c.addMouseListener(ml);
c.addMouseMotionListener(ml);
f.setVisible(true);
}
public static void main(String[] args) {
Dra d = new Dra();
d.disp();
}
public class MosL extends MouseAdapter {
int sx = 0;
int sy = 0;
boolean onDrag = false;
@Override
public void mouseDragged(MouseEvent e) {
if (onDrag) {
int x = e.getX();
int y = e.getY();
Canvas comp = (Canvas) e.getSource();
Graphics g = comp.getGraphics();
// comp.repaint(); << for cleaning up the intermediate lines : doesnt work :(
g.drawLine(sx, sy, x, y);
return;
}
onDrag = true;
sx = e.getX();
sy = e.getY();
System.out.println("Draggg");
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("Released");
if (onDrag)
onDrag = false;
}
}
public class Can extends Canvas {
@Override
public void paint(Graphics g) {
}
}
}
问题: 1)当窗口最小化并恢复时,绘制的线条消失(由于重绘) 2)我想要的是线应该跟随鼠标(当它被拖动时)。最后一行应该从按压点延伸到鼠标释放点。 Rite现在,当鼠标移动时,新线条将被绘制。我不确定如何清理画布中的中间线。
有人可以帮我解决这些问题吗?
答案 0 :(得分:12)
以下是这种“绘画”的一个简单例子:
public static void main ( String[] args )
{
JFrame paint = new JFrame ();
paint.add ( new JComponent ()
{
private List<Shape> shapes = new ArrayList<Shape> ();
private Shape currentShape = null;
{
MouseAdapter mouseAdapter = new MouseAdapter ()
{
public void mousePressed ( MouseEvent e )
{
currentShape = new Line2D.Double ( e.getPoint (), e.getPoint () );
shapes.add ( currentShape );
repaint ();
}
public void mouseDragged ( MouseEvent e )
{
Line2D shape = ( Line2D ) currentShape;
shape.setLine ( shape.getP1 (), e.getPoint () );
repaint ();
}
public void mouseReleased ( MouseEvent e )
{
currentShape = null;
repaint ();
}
};
addMouseListener ( mouseAdapter );
addMouseMotionListener ( mouseAdapter );
}
protected void paintComponent ( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
g2d.setPaint ( Color.BLACK );
for ( Shape shape : shapes )
{
g2d.draw ( shape );
}
}
} );
paint.setSize ( 500, 500 );
paint.setLocationRelativeTo ( null );
paint.setVisible ( true );
}
它会记住所有绘制的形状,只需很小的努力就可以扩展它以绘制你喜欢的任何其他形状。
答案 1 :(得分:5)
在 AWT 包中使用Line2D对象并执行以下步骤:
boolean
variable
以检查点击是第一个还是第一个
第二List
容器以包含Line2D
个对象Can
对象步骤5可以通过以下方式实现:
e.getX()
e.getY()
其中e是鼠标事件,可以通过鼠标侦听器方法的参数加入。
答案 2 :(得分:2)
您应该在awt包中使用Line2D对象,为第一次单击和第二次单击创建x和y值,并使用布尔值确定它是第一次还是第二次单击。然后创建一个Line2D的ArrayList并在Can对象中绘制它们。因此,您可以使用MouseEvent.getX()和getY()在鼠标侦听器中为事件分配x和y值之前和之后的值。