有如下程序:(这个程序是用键盘画出直线的)
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Exercise16_9 extends JFrame {
private DrawLine k = new DrawLine();
public static void main(String[] args) {
JFrame frame = new Exercise16_9();
frame.setSize(600,600);
frame.setTitle("Exercise16_9");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public Exercise16_9() {
add(k);
k.setFocusable(true);
}
static class DrawLine extends JPanel {
private boolean center = false;
Polygon p = new Polygon();
int x;
int y;
public DrawLine() {
// p.addPoint(200,200);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_UP) {
y -= 5;
p.addPoint(x,y);
repaint();
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN) {
y += 5;
p.addPoint(x,y);
repaint();
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT) {
x -= 5;
p.addPoint(x,y);
repaint();
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
x += 5;
p.addPoint(x,y);
repaint();
}
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(!center) {
p.addPoint(getWidth()/2,getHeight()/2);
center = true;
x = p.xpoints[0];
y = p.xpoints[0];
}
g.drawPolyline(p.xpoints,p.ypoints,p.xpoints.length);
}
}
}
在运行的时候,发现多了一条奇怪的直线,结果我把
g.drawPolyline(p.xpoints,p.ypoints,p.xpoints.length);
改为
g.drawPolyline(p.xpoints,p.ypoints,p.npoints);
就可以了。为了解释这个原因,
我反编译了polygon类:
观察到他的addPoint方法:
public void addPoint(int x, int y) {
if (npoints >= xpoints.length || npoints >= ypoints.length) {
int newLength = npoints * 2;
// Make sure that newLength will be greater than MIN_LENGTH and
// aligned to the power of 2
if (newLength < MIN_LENGTH) {
newLength = MIN_LENGTH;
} else if ((newLength & (newLength - 1)) != 0) {
newLength = Integer.highestOneBit(newLength);
}
xpoints = Arrays.copyOf(xpoints, newLength);
ypoints = Arrays.copyOf(ypoints, newLength);
}
xpoints[npoints] = x;
ypoints[npoints] = y;
npoints++;
if (bounds != null) {
updateBounds(x, y);
}
}
发现了
p.xpoints.length
和
p.npoints
是不一样的