Home » Desktop Java » awt » event » Arrow sketch on JFrame example

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Arrow sketch on JFrame example

package com.javacodegeeks.snippets.desktop;

import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class KeyFrame extends JPanel implements KeyListener {

    private Point start = new Point(0, 0);
    private Point end = new Point(0, 0);

    public static void main(String[] args) {

  JFrame jFrame = new JFrame();

  jFrame.setTitle("ArrowSketch");

  jFrame.setSize(300, 300);

  jFrame.addWindowListener(new WindowAdapter() {



@Override


public void windowClosing(WindowEvent e) {


    System.exit(0);


}

  });


  Container p = jFrame.getContentPane();

  p.add(new KeyFrame());


  jFrame.setVisible(true);
    }
    

    public KeyFrame() {

  addKeyListener(this);
    }

    @Override
    public void keyPressed(KeyEvent keyEvent) {

  int key = keyEvent.getKeyCode();

  int i;

  if (keyEvent.isShiftDown()) {


i = 5;

  } else {


i = 1;

  }

  if (key == KeyEvent.VK_LEFT) {


add(-i, 0);

  } else if (key == KeyEvent.VK_RIGHT) {


add(i, 0);

  } else if (key == KeyEvent.VK_UP) {


add(0, -i);

  } else if (key == KeyEvent.VK_DOWN) {


add(0, i);

  }
    }

    @Override
    public void keyReleased(KeyEvent evt) {
    }

    @Override
    public void keyTyped(KeyEvent evt) {
    }

    @Override
    public boolean isFocusTraversable() {

  return true;
    }

    public void add(int x, int y) {

  end.x += x;

  end.y += y;

  Graphics graphics = getGraphics();

  graphics.drawLine(start.x, start.y, end.x, end.y);

  graphics.dispose();

  start.x = end.x;

  start.y = end.y;
    }
}
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of