在像 Microsoft 的 PaintTM 这样的绘图程序中,可用的功能之一是绘制直线。您可以通过按下鼠标来绘制一条直线,以指示该线的起点。然后,在鼠标仍然按下的情况下,您可以移动鼠标(鼠标拖动),并且随着您的移动创建线的终点。当您释放鼠标时,该线将保留。您可以多次重复此过程,在 PaintTM 文档中创建许多不同的线条。
如果您希望在 Java 程序中模拟这种效果,您可以使用 MouseListener(mousePressed 方法)和 MouseMotionListener(mouseDragged 方法)来创建线段。此外,我们希望能够通过顶部的“清除按钮”清除绘制区域。此外,我们想通过在顶部放置一些“颜色按钮”来更改所有线条的颜色。为了完成所有这些,您将需要使用坐标数组,因为每次调用 repaint 时,您都需要重新绘制所有存储的线。*/
import java.awt.*;
import java.awt.event.*; //brings in the ability to read loops by 'event' of something
import javax.swing.*; //interface that extends both the MouseMotionListener and MouseListener interfaces
public class Draw extends JApplet implements MouseListener, MouseMotionListener
{
private int [] x;
private int [] y;
private boolean changed = true;
Display draw;
public void init()
{
draw = new Display(); //use Display not draw
setContentPane(draw); //lets you draw the stuff
draw.setBackground(Color.green); //sets the background color to whatever you want
draw.setFont (new Font("SansSerif", Font.BOLD, 24)); //this sets the font size and type
draw.addMouseListener(this);
draw.addMouseMotionListener(this); //adds the MouseMotionListener
} //to read in actions of the mouse
class Display extends JPanel
{
public void paintComponent(Graphics g) //Graphics __ <--name can be anything
{
super.paintComponent(g); //paintComponent(__) <-- __ has to match w/ the one above
g.setColor(Color.black); //these are the 5 buttons at the top
g.fillRect(2, 2, 95, 70); //
g.setColor(Color.red); //
g.fillRect(100, 2, 95, 70); //
g.setColor(Color.blue); //
g.fillRect(198, 2, 95, 70); //
g.setColor(Color.gray); //
g.fillRect(296, 2, 95, 70); //
g.setColor(Color.cyan); //
g.fillRect(394, 2, 95, 70); //
g.setColor(Color.white);
g.drawString("RESET", 10, 45);
g.drawString("RED", 125, 45);
g.drawString("BLUE", 215, 45);
g.drawString("GRAY", 310, 45);
g.drawString("CYAN", 410, 45);
}
}
public void mousePressed(MouseEvent evt)
{
int x = evt.getX();
int y = evt.getY();
changed = false;
if (y > 2 && y < 70)
{
changed = true;
if (x > 2 && x < 100)
{
draw.repaint();
}
else
changed = false;
}
}
public void mouseDragged(MouseEvent evt)
{
}
public void mouseReleased(MouseEvent evt) {}
public void mouseMoved(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {} // Some empty routines.
public void mouseExited(MouseEvent evt) {} // (Required by the MouseListener
public void mouseClicked(MouseEvent evt) {} // and MouseMotionListener interfaces).
}
Run Code Online (Sandbox Code Playgroud)
mousePressed 应该在有人点击时触发(即当他们按下鼠标上的按钮时 - 而不是释放)。
mouseDragged 应该在人按下鼠标按钮后触发,然后移动鼠标。
因此,您可以考虑将鼠标的 x,y 坐标存储在 mousePressed 上,然后在 mouseDragged 触发时在该 x,y 位置和当前鼠标 x,y 位置之间绘制一条线。