关于paintComponent的小细节(Graphics 类)

题目:编写一个程序,使用箭头键绘制线段。

对于这个题目,我开始写的代码是这样的

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Exercise16_9 extends JFrame {
    
	private KeyLinePanel p = new KeyLinePanel();
	public Exercise16_9() {
		add(p);
		
		p.setFocusable(true);
	}
	public static void main(String[] args) {
		Exercise16_9 frame = new Exercise16_9();
		frame.setTitle("Exercise16_9");
		frame.setSize(300, 200);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
	static class KeyLinePanel extends JPanel {
		private int x1 = 50;
		private int y1 = 50;
		private int x2 = 50;
		private int y2 = 50;
		public KeyLinePanel() {
			addKeyListener(new KeyAdapter() {
				public void keyPressed(KeyEvent e) {
					switch(e.getKeyCode()) {
						case KeyEvent.VK_UP: y2 = y1 - 2; break;
						case KeyEvent.VK_DOWN: y2 = y1 + 2; break;
						case KeyEvent.VK_LEFT: x2 = x1 - 2; break;
						case KeyEvent.VK_RIGHT: x2 = x1 + 2; break;
					}
					repaint();
				}
			});
		}
		protected void paintComponent(Graphics g) {
		    
			super.paintComponent(g);
			g.drawLine(x1, y1, x2, y2);
			x1 = x2;
			y1 = y2;
		}
	}
}

结果运行时发现,运行结果更预期结果不一样,然后我去掉了
super.paintComponent(g);
这条语句,就O了。

我注意到了

super.paintComponent(g);

这个方法,用这个方法调用父类中定义的paintComponent方法,该方法的作用是确保在显示新的图画之前清空视图区域

你可能感兴趣的:(awt,java,Graphics,j2se)