0

I'm not sure why when I press w my rectangle doesn't adjust accordingly. Do I have my focus set up right, or do I need to request it from a separate class? Should I be doing this in my drawingComponent class or in my "core" class?

package scratch;


import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.*;

public class drawingComponent extends JComponent implements KeyListener {

    Rectangle hello = new Rectangle(300, 100, 50, 50);

    public void paintComponent(Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(new Color(255,25,0));
        g2.setFont(new Font("monospace", Font.BOLD+Font.ITALIC, 30));
        g2.drawString("nothing yet",300,320);
        g2.fill(hello);

    }


    @Override
    public void keyPressed(KeyEvent e) {

        if(e.getKeyCode() == KeyEvent.VK_W){

             hello.setLocation(hello.x-50, hello.y);
             repaint();

        }


    }

    @Override
    public void keyReleased(KeyEvent e) {


    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

}

I have solved the problem by adding the following to my drawingComponent class.

setFocusable(true);
requestFocus();
addKeyListener(this);
2

1 Answer 1

2

You want to use Key Bindings, not a KeyListener for several reasons, but one being that you don't have to worry so much about focus with Key Bindings. Also, you'll want to in the future post a minimal example program that we can test, run and modify, something like this:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class DrawingComponent extends JPanel {
   private static final int PREF_W = 800;
   private static final int PREF_H = 600;
   private static final Color RECT_COLOR = new Color(255,25,0);
   private Rectangle rect = new Rectangle(300, 100, 50, 50);

   public DrawingComponent() {
      setUpKeyBindings();
   }

   private void setUpKeyBindings() {
      int condition = WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();

      KeyStroke wStroke = KeyStroke.getKeyStroke(KeyEvent.VK_W, 0);
      inputMap.put(wStroke, wStroke.toString());
      actionMap.put(wStroke.toString(), new WAction());
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setColor(RECT_COLOR);
      g2.fill(rect);
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private class WAction extends AbstractAction {
      @Override
      public void actionPerformed(ActionEvent e) {
         rect.setLocation(rect.x-50, rect.y);
         repaint();
      }
   }

   private static void createAndShowGui() {
      DrawingComponent mainPanel = new DrawingComponent();

      JFrame frame = new JFrame("DrawingComponent");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Also, call the super's paintComponent method in your override, else your JPanel won't erase the old images.

12
  • thank you for the answer, kind sir. i didn't think my question was this complex. i appreciate your insight, but for now will continue with keylistener until i understand how that works.
    – wilkers
    Nov 9, 2014 at 18:08
  • 1
    @wilkers: your question as it is currently currently presented is essentially, "why isn't the code that I'm not showing you not working" since you don't know exactly where the error lies, and so your posted code does not show it. If you still want to see why your KeyListener doesn't work, then you'll need to create and post your MCVE. But regardless, if you want to solve your problem and code this correctly, then please read the link I've provided above on how to use Key Bindings. Nov 9, 2014 at 18:11
  • 1
    @wilkers: Please don't take offense, but I'll wager that I am more familiar with when to use KeyListeners and when to use Key Bindings than you, and that when using Key Bindings, the issue of focus becomes a non-issue. But I'm not here to force you to believe me or to follow my advice. Rather I'm here just to give my advice, advice which you can follow or not as you choose. I also still remain firm in my recommendation for you to create an post an MCVE if you want to see why your code is not working. Nov 9, 2014 at 18:18
  • no offense taken at all. this specific code was set up for example , to apply to a larger code that cannot accept a universal key binding. i dont need to set up a MCVE, and your comments are not helping . thank you
    – wilkers
    Nov 9, 2014 at 18:22
  • 1
    @wilkers I have to agree with HovercraftFullOfEels, Key bindings are the solution and will resolve your focus related issues without nasty hacks or work arounds which may or may not work on different platforms and systems Nov 10, 2014 at 0:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.