zoukankan      html  css  js  c++  java
  • 16.9

     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 }
    Test_16_9.java

    效果图:

    有一个小问题,暂时没解决。对于取得JPanel的getWidth()和getHeight(),无法在paintComponent()外面取得,在外面取得的值为0。而如果将x1 y1放入内部的话,又无法更新x1 y1的位置。

  • 相关阅读:
    Windows API 第六篇 GetLocalTime
    _itoa _itow _itot atoi atof atol
    Window API 第五篇 WTSEnumerateProcesses
    获取计算机以及本机信息API
    Windows API 第四篇 文件操作
    [软工顶级理解组] 团队介绍和采访!
    2019 SDN上机第1次作业
    第01组 团队项目-需求分析报告
    团队项目-选题报告
    第二次结对编程作业
  • 原文地址:https://www.cnblogs.com/wanjiang/p/5638893.html
Copyright © 2011-2022 走看看