蚀刻草图问题

时间:2013-09-19 18:40:16

标签: java draw etch

我正在用java编写程序,因此它可以模仿蚀刻草图。我有它画线,但我似乎无法得到它画一条连续线。我是初学者,这将得到很多帮助。谢谢 !

这是我目前的代码..

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;



   public class Sketch
       {
    public static void main (String [] args){
    SketchFrame frame = new SketchFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   frame.setVisible(true); }}


  // JFrame: defines app's window
  class SketchFrame extends JFrame
   {
  public static final int WIDTH = 600;
  public static final int HEIGHT = 600;
  public static final String FRAME_TITLE = "Sketch";

 public SketchFrame()
   {
  setTitle(FRAME_TITLE);
  setSize(WIDTH, HEIGHT);

  add( new SketchPanel() );
   }
   }



  class SketchPanel extends JPanel 
  implements KeyListener {

private int xStart = 0;
private int yStart = 0;
private int xEnd = 0;
private int yEnd = 0;


    public SketchPanel() {
    addKeyListener(this);
    setFocusable(true);
 }


  public void keyPressed(KeyEvent e) {

  if (e.getKeyCode() == KeyEvent.VK_UP) {
      yStart = yEnd;
      xStart = xEnd;
      yEnd -= 50;


  }
  else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
      yStart = yEnd;
      xStart = xEnd;
      yEnd += 10;

  }
  else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
      xStart = xEnd;
      yStart = yEnd;
      xEnd -= 10;

  }
  else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
      xStart = xEnd;
      yStart = yEnd;
      xEnd += 10;

  }  

  repaint();
  }


 public void paintComponent(Graphics g) {

    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;

     g2.setColor(Color.RED);
     g2.drawLine(drawXStart(), drawYStart(), drawXEnd(), drawYEnd());

}

  private int drawXStart() {
      return (getWidth() / 2) + xStart;
  }

  private int drawXEnd() {
      return (getWidth() / 2) + xEnd;
  }

  private int drawYStart() {
      return (getHeight() / 2) + yStart;
  }

  private int drawYEnd() {
      return (getHeight() /2) + yEnd;
  }


public void keyReleased(KeyEvent e) {}



public void keyTyped(KeyEvent e) {}
    }

1 个答案:

答案 0 :(得分:0)

问题是SketchPanel不记得先前绘制的线条。您可能应该使用BufferedImage进行绘制(您可以在keyPressed中进行绘制),并将该图像绘制到paintComponent中的Graphics对象上。