import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Liikumine3 extends JPanel implements ActionListener, KeyListener{ int omax=30; int omaxsamm=1; int omay=15; int omaysamm=0; int d=15; Timer t=new Timer(100, this); public Liikumine3(){ t.start(); setFocusable(true); addKeyListener(this); } public void paintComponent(Graphics g){ super.paintComponent(g); g.fillRect(omax, omay, d, d); } public void keyPressed(KeyEvent e){ int kood=e.getKeyCode(); System.out.println(kood); if(kood==KeyEvent.VK_LEFT){omaxsamm--;} if(kood==KeyEvent.VK_RIGHT){omaxsamm++;} if(kood==KeyEvent.VK_UP){omaysamm--;} if(kood==KeyEvent.VK_DOWN){omaysamm++;} } public void keyReleased(KeyEvent e){} public void keyTyped(KeyEvent e){} public void liigu(){ if(omax+omaxsamm+d>getWidth()){omaxsamm=0;} if(omay+omaysamm+d>getHeight()){omaysamm=0;} if(omax+omaxsamm<0){omaxsamm=0;} if(omay+omaysamm<0){omaysamm=0;} omax+=omaxsamm; omay+=omaysamm; repaint(); } public void actionPerformed(ActionEvent e){ if(e.getSource()==t){ liigu(); } } public static void main(String[] arg){ JFrame f=new JFrame("Liikumine"); f.add(new Liikumine3()); f.setSize(300, 300); f.setVisible(true); } }