import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Liikumine4 extends JPanel implements ActionListener, KeyListener{ //Pange iseliikuja ja oma liigutatav ühele lehele int x=100; int xsamm=2; int y=50; int ysamm=3; int omax=30; int omaxsamm=1; int omay=15; int omaysamm=0; int d=15; Timer t=new Timer(100, this); public Liikumine4(){ t.start(); setFocusable(true); addKeyListener(this); } public void paintComponent(Graphics g){ super.paintComponent(g); g.fillRect(omax, omay, d, d); g.drawRect(x, y, d, d); } public void keyPressed(KeyEvent e){ int kood=e.getKeyCode(); 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; if(xsamm>0){ if(x+xsamm+d>getWidth()){ xsamm=-xsamm; } } else { if(x+xsamm<0){ xsamm=-xsamm; } } if(ysamm>0){ if(y+ysamm+d>getHeight()){ ysamm=-ysamm; } } else { if(y+ysamm<0){ ysamm=-ysamm; } } y=y+ysamm; x=x+xsamm; 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 Liikumine4()); f.setSize(300, 300); f.setVisible(true); } }