Advertisement
Oslapas

Untitled

Nov 13th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.22 KB | None | 0 0
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4.  
  5. public class KeyBindings extends JFrame {
  6.  
  7.     private static final int D_W = 500;
  8.     private static final int D_H = 200;
  9.     int x = 0;
  10.     int y = 0;
  11.  
  12.     DrawPanel drawPanel = new DrawPanel();
  13.  
  14.     public KeyBindings() {
  15.         ActionListener listener = new AbstractAction() {
  16.             public void actionPerformed(ActionEvent e) {
  17.                 if (x >= D_W) {
  18.                     x = 0;
  19.                     drawPanel.repaint();
  20.                 } else {
  21.                     x += 10;
  22.                     drawPanel.repaint();
  23.                 }
  24.             }
  25.         };
  26.         Timer timer = new Timer(100, listener);
  27.         timer.start();
  28.         add(drawPanel);
  29.  
  30.         pack();
  31.         setDefaultCloseOperation(EXIT_ON_CLOSE);
  32.         setLocationRelativeTo(null);
  33.         setVisible(true);
  34.     }
  35.  
  36.     private class DrawPanel extends JPanel {
  37.  
  38.         protected void paintComponent(Graphics g) {
  39.             super.paintComponent(g);
  40.             g.setColor(Color.GREEN);
  41.             g.fillRect(x, y, 50, 50);
  42.         }
  43.  
  44.         public Dimension getPreferredSize() {
  45.             return new Dimension(D_W, D_H);
  46.         }
  47.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement