我正在用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) {}
}