Skip to content

Instantly share code, notes, and snippets.

@ornirus
Created October 3, 2014 07:53
Show Gist options
  • Save ornirus/52edc2de0930f4f5fcae to your computer and use it in GitHub Desktop.
Save ornirus/52edc2de0930f4f5fcae to your computer and use it in GitHub Desktop.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Movement extends JFrame
implements ActionListener {
private JButton upButton, downButton, rightButton, leftButton;
private JPanel panel;
private int xPos;
private int yPos;
public static void main(String[] args) {
Movement frame = new Movement();
frame.setSize(700, 500);
frame.createGUI();
frame.setVisible(true);
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout() );
panel = new JPanel();
panel.setPreferredSize(new Dimension(600, 400));
panel.setBackground(Color.white);
window.add(panel);
upButton = new JButton("Up");
window.add(upButton);
upButton.addActionListener(this);
downButton = new JButton("Down");
window.add(downButton);
downButton.addActionListener(this);
rightButton = new JButton("Right");
window.add(rightButton);
rightButton.addActionListener(this);
leftButton = new JButton("Left");
window.add(leftButton);
leftButton.addActionListener(this);
xPos = 300;
yPos = 200;
panel.setFocusable(true);
panel.requestFocus();
panel.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case 87:
case KeyEvent.VK_UP:
moveCircle(0, yPos - 15);
break;
case 68:
case KeyEvent.VK_RIGHT:
moveCircle(xPos + 15, 0);
break;
case 83:
case KeyEvent.VK_DOWN:
moveCircle(0, yPos + 15);
break;
case 65:
case KeyEvent.VK_LEFT:
moveCircle(xPos - 15, 0);
break;
}
System.out.println(e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
});
}
public void moveCircle(int x, int y) {
Graphics paper = panel.getGraphics();
paper.fillOval(xPos, yPos, 15, 15);
paper.setColor(Color.white);
paper.fillOval(xPos, yPos, 15, 15);
yPos = yPos + y;
xPos = xPos + x;
xPos = (xPos + 585) % 585;
yPos = (yPos + 385) % 385;
paper.setColor(Color.black);
paper.fillOval(xPos, yPos, 15, 15);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == upButton) {
moveCircle(0, -15);
}
if (source == downButton) {
moveCircle(0, 15);
}
if (source == rightButton) {
moveCircle(15, 0);
}
if (source == leftButton) {
moveCircle(-15, 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment