java中的一个画图小细节

22 篇文章 0 订阅
3 篇文章 0 订阅

有如下程序:(这个程序是用键盘画出直线的)

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
是不一样的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值