写在下面的 BasicLinePix 类中,我尝试创建一个程序,该程序允许用户通过按住 shift 键同时按住鼠标按钮并将其拖动到端点来绘制线条。问题是当鼠标被释放时,这条线就消失了。我试图让线条显示在面板中,并显示以相同方式绘制的多条线条。
我的代码如下所示:
// this method overrides the paint method defined in JFrame
public void paint(Graphics g) {
super.paint(g);
}
// Inner class - instances of this class handle action events
private class EventHandler implements ActionListener, MouseListener,
MouseMotionListener {
private Point startPoint = null; // line's start point
private Point endPoint = null; // line's most recent end point
public void actionPerformed(ActionEvent arg0) {
if (arg0.getActionCommand().equals("Exit")) {
statusLabel.setText("Exiting program...");
System.exit(0);
}
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
if (e.isShiftDown()) {
// record starting point for line
startPoint = new Point(e.getX(), e.getY());
// initialize endPoint
endPoint = startPoint;
}
if (e.isControlDown()) {
Graphics g = drawingPanel.getGraphics();
g.drawString("Hello", e.getX(), e.getY());
}
}
@Override
public void mouseReleased(MouseEvent arg0) {
//repaint the frame and its contents
//this executes the paint method defined above
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
if (e.isShiftDown()) {
// Implement rubber-band cursor
Graphics g = drawingPanel.getGraphics();
g.setColor(Color.black);
g.setXORMode(drawingPanel.getBackground());
// REDRAW the line that was drawn
// most recently during this drag
// XOR mode means that yellow pixels turn black
// essentially erasing the existing line
drawLine(g, startPoint, endPoint);
// Update the end point of the line to current mouse position
endPoint = new Point(e.getX(), e.getY());
// Draw line to current mouse position
// XOR mode: yellow pixels become black
// black pixels, like those from existing lines, temporarily
// become
// yellow
drawLine(g, startPoint, endPoint);
}
}
@Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
private void drawLine(Graphics g, Point start, Point end) {
if (startPoint != null && endPoint != null) {
int startX = ((Double) start.getX()).intValue();
int startY = ((Double) start.getY()).intValue();
int endX = ((Double) end.getX()).intValue();
int endY = ((Double) end.getY()).intValue();
g.drawLine(startX, startY, endX, endY);
}
}
}
}
任何帮助将不胜感激!