- import javax.swing.*;
- import java.awt.geom.*;
- import java.util.*;
- import java.awt.event.*;
- import java.awt.*;
- public class Sketch {
- public static void main(String []args){
- SketchFrame sf=new SketchFrame();
- sf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- sf.show();
- }
- }
- class SketchFrame extends JFrame{
- public SketchFrame(){
- setTitle("phenix");
- setSize(this.DEFAULT_WIDTH,this.DEFAULT_HEIGHT);
- SketchPanel panel=new SketchPanel();
- Container contentPane=getContentPane();
- contentPane.add(panel);
- }
- public static final int DEFAULT_WIDTH=300;
- public static final int DEFAULT_HEIGHT=400;
- }
- class SketchPanel extends JPanel{
- private Point2D last;
- private ArrayList lines;
- private static final int SMALL_INCREMENT=1;
- private static final int LARGE_INCREMENT=5;
- public SketchPanel(){
- last=new Point2D.Double(100,100);
- lines=new ArrayList();
- KeyHandler listener=new KeyHandler();
- addKeyListener(listener);
- setFocusable(true);
- }
- public void add(int dx,int dy){
- Point2D end=new Point2D.Double(last.getX()+dx,last.getY()+dy);
- Line2D line=new Line2D.Double(last,end);
- lines.add(line);
- repaint();
- last=end;
- System.out.println("哈哈");
- }
- public void paintComponent(Graphics g){
- super.paintComponent(g);
- Graphics2D g2=(Graphics2D)g;
- for(int i=0;i<lines.size();i++){
- g2.draw((Line2D)lines.get(i));
- }
- }
- private class KeyHandler implements KeyListener
- {
- public void keyPressed(KeyEvent event){
- int keyCode=event.getKeyCode();
- //set distance
- int d;
- if(event.isShiftDown()){
- d=LARGE_INCREMENT;
- System.out.println("shift key is down");
- }
- else
- {
- d=SMALL_INCREMENT;
- }
- if(keyCode==KeyEvent.VK_LEFT){
- add(-d,0);
- }
- else
- if(keyCode==KeyEvent.VK_RIGHT){
- add(d,0);
- }
- else
- if(keyCode==KeyEvent.VK_UP){
- add(0,-d);
- }
- else
- if(keyCode==KeyEvent.VK_DOWN)
- {
- add(0,d);
- }
- }
- public void keyReleased(KeyEvent event){
- }
- public void keyTyped(KeyEvent event){
- char keyChar=event.getKeyChar();
- int d;
- if(Character.isUpperCase(keyChar)){
- d=LARGE_INCREMENT;
- }
- else{
- d=SMALL_INCREMENT;
- }
- if(keyChar=='h'){
- add(-d,0);
- }else
- if(keyChar=='l'){add(d,0);}
- else if(keyChar=='k')add(0,-d);
- else if(keyChar=='j')add(0,d);
- }
- }
- }
core java 中的sketch小游戏
最新推荐文章于 2024-09-10 10:21:38 发布