![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 5 public class Test_16_9 extends JFrame{ 6 private JP JP1 = new JP(); 7 public Test_16_9(){ 8 int i = JP1.getWidth(); 9 add(JP1); 10 JP1.setFocusable(true); 11 } 12 13 public static void main(String[] args) { 14 // TODO Auto-generated method stub 15 Test_16_9 t1 = new Test_16_9(); 16 t1.setTitle("Test_16.9"); 17 t1.setSize(300,300); 18 t1.setLocationRelativeTo(null); 19 t1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 20 t1.setVisible(true); 21 } 22 23 static class JP extends JPanel{ 24 private int x1 = 150; 25 private int y1 = 150; 26 private int x2 =x1,y2 =y1; 27 28 public JP(){ 29 addKeyListener(new KeyAdapter(){ 30 31 public void keyPressed(KeyEvent e) { 32 // TODO Auto-generated method stub 33 switch(e.getKeyCode()){ 34 case KeyEvent.VK_UP: update();y2 = y2 -20; break; 35 case KeyEvent.VK_DOWN: update();y2 =y2 + 20;break; 36 case KeyEvent.VK_LEFT: update();x2 =x2 - 20;break; 37 case KeyEvent.VK_RIGHT: update();x2 =x2 + 20;break; 38 } 39 repaint(); 40 } 41 }); 42 } 43 protected void paintComponent(Graphics g){ 44 // super.paintComponent(g); 45 46 g.drawLine(x1, y1, x2, y2); 47 48 System.out.println("("+x1+","+y1+") ("+x2+","+y2+")"); 49 } 50 protected void update(){ 51 x1 = x2; y1 = y2; 52 } 53 } 54 }
效果图:
有一个小问题,暂时没解决。对于取得JPanel的getWidth()和getHeight(),无法在paintComponent()外面取得,在外面取得的值为0。而如果将x1 y1放入内部的话,又无法更新x1 y1的位置。