Results 1 to 3 of 3
  1. #1
    alphasil is offline Member
    Join Date
    Jan 2012
    Posts
    33
    Rep Power
    0

    Default KeyListener partial problem

    Hi

    I have 3 classes.

    This is my main class
    Java Code:
    import java.awt.Color;
    import java.awt.Event;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    
    
    /**
     * @author Gil
     *
     */
    public class main extends JFrame implements KeyListener{
    
    	private static final long serialVersionUID = 1L;
    	private jogador jg;
    	private Image img;
    	private Graphics graphics;
    	public static boolean movEsquerda = false;
    	public static boolean movDireita = false;
    	
    	//Fica static por causa do método atualizar
    
    	public main()
    	{
    
    		setTitle("Trabalho Final GMC");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(600,400);
    		setBackground(Color.WHITE);
    		setResizable(true);
    		//Adiciona "escuta de keys"
    		addKeyListener(this);
    		//Poe a janela como visivel
    		setVisible(true);
    
    		//Canhão
    		jg= new jogador(300, 350 , 20, 20,"imagens/cannon.gif");
    
    		//Bugs
    
    	}
    
    	public void paint(Graphics g)
    	{
    		img = createImage(getWidth(), getHeight());
    		graphics =img.getGraphics();
    		g.fillRect(0, 0, getWidth(), getHeight());
    		paintComponent(graphics);
    		g.drawImage(img, 0, 0, null);
    		repaint();
    	}
    
    	public void paintComponent(Graphics g)
    	{
    		jg.desenho(g);
    		jg.atualizar(this, 1);
    	}
    	
    	public void ActionPerformed(ActionEvent e)
    	{
    		repaint();
    	}
    
    	@Override
    	public void keyPressed(KeyEvent e) 
    	{
    		if(e.getKeyCode() == KeyEvent.VK_LEFT)
    		{
    			movEsquerda=true;
    		}
    		else if(e.getKeyCode() == KeyEvent.VK_RIGHT)
    		{
    			movDireita=true;
    		}
    	}
    
    	@Override
    	public void keyReleased(KeyEvent e) 
    	{
    		if(e.getKeyCode() == KeyEvent.VK_LEFT)
    		{
    			movEsquerda=false;
    		}
    		else if(e.getKeyCode() == KeyEvent.VK_RIGHT)
    		{
    			movDireita=false;
    		}
    
    	}
    	
    	public static int getPosX() 
    	{
    		return getPosX();
    	}
    
    	@Override
    	public void keyTyped(KeyEvent e) {
    		// TODO Auto-generated method stub
    
    	}
    
    	public static void main(String args[])
    	{
    		new main();
    	}
    Then i have Objet class
    Java Code:
    import java.awt.Graphics;
    import java.awt.Image;
    
    //Abstract porque Não se pode criar uma instância desta classe
    public abstract class Objetos {
    	
    	protected Image jog;
    	protected int posX;
    	protected int posY;
    	protected int altura;
    	protected int largura;
    
    	//Não cria uma instância, as mesmas estão nas subclasses
    	abstract void desenho(Graphics g);
    	
    	abstract void atualizar(final main principal, final int id);
    	
    	abstract Image getImage(String jog);
    	
    	//Retorno 
    	public Image getJog() {
    		return jog;
    	}
    	
    	//Definição
    	public void setJog(Image jog) {
    		this.jog = jog;
    	}
    
    	public int getPosX() {
    		return posX;
    	}
    
    	public void setPosX(int posX) {
    		this.posX = posX;
    	}
    
    	public int getPosY() {
    		return posY;
    	}
    
    	public void setPosY(int posY) {
    		this.posY = posY;
    	}
    
    	public int getAltura() {
    		return altura;
    	}
    
    	public void setAltura(int altura) {
    		this.altura = altura;
    	}
    
    	public int getLargura() {
    		return largura;
    	}
    
    	public void setLargura(int largura) {
    		this.largura = largura;
    	}	
    }
    And finally i have my player class
    Java Code:
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    //Classe do jogador, pede imagem e posições
    public class jogador extends objetos
    {
    	/**Cria a instância de jogadores
    protected Image jog;
    protected int posX;
    protected int posY;
    protected int altura;
    protected int largura;
    	 */
    	public jogador(final int posX, final int posY, final int altura, final int largura, final String jog)
    	{
    		this.jog= getImage(jog);
    		this.posX= posX;
    		this.posY= posY;
    		this.altura=altura;
    		this.largura=largura;
    	}
    	public void desenho(Graphics g)
    	{
    		g.drawImage(jog, posX, posY, altura, largura, null);
    
    	}
    
    	@Override
    	Image getImage(String jog) {
    		return Toolkit.getDefaultToolkit().getImage(jog);
    	}
    	public void esquerda()
    	{
    		posX--;
    	}
    	public void direita()
    	{
    		posX++;
    
    	}
    	public void disparar()
    	{
    		// TODO Auto-generated method stub
    
    	}
    }
    The problem is when i use the left and right keys, i only see a small movement instead of going from left to right, my image only moves in the first keyPressed...then the image stop forever.

    Whats wrong?

    Thanks

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: KeyListener partial problem

    Don't use KeyListeners for Swing GUI's but instead use Key Bindings. For e.g.,

    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.RenderingHints;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class Main2 extends JPanel {
       private static final int PREF_W = 400;
       private static final int PREF_H = PREF_W;
       private static final int OVAL_W = 15;
       private int x = 150;
       private int y = 150;
       private JMenuBar menuBar;
       private JMenu file;
       private JMenuItem newGame;
       private JMenuItem checkScore;
       private JMenuItem exitGame;
       private Font font = new Font("Arial", Font.ITALIC, 30);
    
       public Main2() {      
          menuBar = new JMenuBar();
          file = new JMenu("File");
          newGame = new JMenuItem("New Game");
          checkScore = new JMenuItem("Check High Scores");
          exitGame = new JMenuItem("Close Game");
    
          menuBar.add(file);
          file.add(newGame);
          file.add(checkScore);
          file.addSeparator();
          file.add(exitGame);
    
          addKeyBinding();
       }
    
       public JMenuBar getMenuBar() {
          return menuBar;
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, 
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
          g.setFont(font);
          g.drawString("Hello World", 100, 200);
    
          g.setColor(Color.red);
          g.drawOval(x, y, OVAL_W, OVAL_W);
          g.fillOval(x, y, OVAL_W, OVAL_W);
       }
    
       private void addKeyBinding() {
          int condition = WHEN_IN_FOCUSED_WINDOW;
          InputMap inputMap = getInputMap(condition);
          ActionMap actionMap = getActionMap();
    
          for (final MyDirection dir : MyDirection.values()) {
             KeyStroke keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0);
             inputMap.put(keyStroke, dir.toString());
             actionMap.put(dir.toString(), new AbstractAction() {
    
                @Override
                public void actionPerformed(ActionEvent evt) {
                   int newX = x + dir.getxTrans();
                   int newY = y + dir.getyTrans();
    
                   newX = Math.min(newX, PREF_W - 2 * OVAL_W);
                   newX = Math.max(newX, OVAL_W);
                   newY = Math.min(newY, PREF_H - 2 * OVAL_W);
                   newY = Math.max(newY, OVAL_W);
    
                   x = newX;
                   y = newY;
                   repaint();
                }
             });
          }
       }
    
       enum MyDirection {
          UP(KeyEvent.VK_UP, 0, -5), DOWN(KeyEvent.VK_DOWN, 0, 5), 
          LEFT(KeyEvent.VK_LEFT, -5, 0), RIGHT(KeyEvent.VK_RIGHT, 5, 0);
    
          private int keyCode;
          private int xTrans;
          private int yTrans;
    
          private MyDirection(int keyCode, int xTrans, int yTrans) {
             this.keyCode = keyCode;
             this.xTrans = xTrans;
             this.yTrans = yTrans;
          }
    
          public int getKeyCode() {
             return keyCode;
          }
    
          public int getxTrans() {
             return xTrans;
          }
    
          public int getyTrans() {
             return yTrans;
          }
    
    
       }
    
       private static void createAndShowGui() {
          Main2 main = new Main2();
    
          JFrame frame = new JFrame("Main2");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(main);
          frame.setJMenuBar(main.getMenuBar());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }

  3. #3
    alphasil is offline Member
    Join Date
    Jan 2012
    Posts
    33
    Rep Power
    0

    Default Re: KeyListener partial problem

    Hi

    Thanks, but i have already made some progress, now i can move the object to down left corner...but don't move in the opposite direction
    Java Code:
    void atualizar(final main principal, final int id) 
    	{
    		if (id==1)
    		{
    			if(main.movEsquerda)
    			{
    				if(!(posX<10))
    				{
    					posX--;
    				}
    				else if(main.movDireita)
    				{
    					if(!(posX>main.getPosX() -530))
    					{	
    						posX++;
    					}
    				}
    			}
    		}
    My area is 600*400 so the 530 should be working, right?

Similar Threads

  1. A problem with KeyListener
    By Reskaillev in forum New To Java
    Replies: 4
    Last Post: 07-22-2011, 03:29 AM
  2. Partial message problem using nio socket
    By perl010101 in forum Advanced Java
    Replies: 1
    Last Post: 05-26-2011, 12:43 AM
  3. Partial message problem using nio socket
    By perl010101 in forum New To Java
    Replies: 0
    Last Post: 05-25-2011, 10:26 PM
  4. AWT KeyListener Problem
    By plm-pusik in forum New To Java
    Replies: 15
    Last Post: 11-10-2010, 04:38 PM
  5. KeyListener problem
    By siyi90 in forum AWT / Swing
    Replies: 7
    Last Post: 02-08-2010, 11:16 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •