Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///////////////////////////////////////////////////////////////////////////////////////
- Create file MainWindow.java
- //////////////////////////////////////////////////////////////////////////////////////
- public class MainWindow
- {
- import javax.swing.JFrame;
- public static void main(String args[])
- {
- JFrame f = new JFrame("This is a basic app");
- //Adding the JPanel to the JFrame
- f.add(new PaintSheet());
- //Resize JFrame relative to JPanel size
- f.frame.pack();
- //Set position in the middle
- f.frame.setLocationRelativeTo(null);
- //Close if pressing X
- f.frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- //Show the window
- f.frame.setVisible(true);
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////
- Create file PaintSheet.java
- //////////////////////////////////////////////////////////////////////////////////////
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.event.KeyEvent;
- import java.awt.event.KeyListener;
- import java.awt.Color;
- import javax.swing.JPanel;
- public class PaintSheet extends JPanel implements KeyListener{
- //Set the JPanel's size to 400x400
- private double width = 400, height = 400;
- //First x && y position
- private double x = 200,y = 200;
- private double dx, dy;
- public PaintSheet()
- {
- //Set the JPanel size
- this.setSize((int)this.width, (int)this.height);
- //Add keyListener
- this.addKeyListener(this);
- //IMPORTANT - THIS LINE ALLOWS JPANEL TO GET KEY PRESS
- this.setFocusable(true);
- }
- @Override
- public void paintComponent(Graphics g)
- {
- //Request focus to allow key pressing
- super.requestFocus();
- super.paintComponent(g);
- Graphics2D g2d = (Graphics2D) g;
- g2d.setColor(Color.black);
- g2d.fillOval((int)this.x, (int)this.y, 40, 40);
- //Sleep the thread to avoid super-moving
- try {
- Thread.sleep(10);
- } catch (InterruptedException ex) { }
- repaint();
- }
- public void keyReleased(KeyEvent e){}
- public void keyTyped(KeyEvent e){}
- public void keyPressed(KeyEvent e)
- {
- if(e.getKeyCode() == KeyEvent.VK_RIGHT)
- this.dx = 1;
- if(e.getKeyCode() == KeyEvent.VK_LEFT)
- this.dx = -1;
- if(e.getKeyCode() == KeyEvent.VK_DOWN)
- this.dy = 1;
- if(e.getKeyCode() == KeyEvent.VK_UP)
- this.dy = -1;
- this.x += this.dx;
- this.y += this.dy;
- this.dx = 0;
- this.dy = 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment