0

When the code runs I get no errors. It runs all parts except for my keypress. Where something is going wrong.

import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;

// Inheriting the JFrame class
public class Main extends JFrame {
    Scanner d = new Scanner(System.in);
    //Defining the Frame
    JFrame f;
    char input;
    int x = 250;
    int y = 100;

    //Constructor
    Main()
    {

        ImageIcon p = new ImageIcon("Player.png");
        JLabel b = new JLabel(p);
        b.setBounds(x, y, 50, 50);
        add(b);
System.out.println("started");


        b.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {

        System.out.println("*Event Listener Run*");
                input = e.getKeyChar();
                if (input == 'w')
                {
          y-=50;
                }
                else if (input == 'a')
                {
          x-=50;
                }
                else if (input == 's')
                {
          y+=50;
                }
                else if (input == 'd')
                {
          x+=50;
                }
            System.out.println("Cords: "+x+","+y);

        b.setBounds(x, y, 50, 50);
            }
            public void keyTyped(KeyEvent e){
      }
            public void keyReleased(KeyEvent e){
        System.out.println("keyReleased");
      }
        });

        //Set up Window
    System.out.println("*setup window*");
        setSize(800, 600);
        setLayout(null);
        setVisible(true);

    System.out.println("*setup window done*");
    }

  public static void main(String[] args){
    // Create the window
    new Main();
  }
}

I added error println's to see if some of the code isn't running, however it all is.

FZs
  • 16,581
  • 13
  • 41
  • 50
Ricky
  • 11
  • 5
  • 2
    Please post your code in the question, not a link to an image of code. How can we copy and paste an image of code onto our machines to run and test it? – achAmháin Apr 18 '19 at 16:27
  • Use KeyBinder instead of KeyListener. – George Z. Apr 18 '19 at 16:37
  • 1
    judging by your code you are trying to get the jLabel to move around the screen when a key is pressed, if that is the case don't place the KeyListener on the label, instead just: `addKeyListener(new KeyListener() { ... ` – this_is_cat Apr 18 '19 at 16:38
  • You should be using [Key Bindings](https://tips4java.wordpress.com/2008/10/10/key-bindings/). – camickr Apr 18 '19 at 18:43
  • Please explain, what does it mean: *something is going wrong*? – FZs Apr 18 '19 at 18:45
  • @FZs you edited their answer to "something is going wrong?" when what they asked was "WHERE are they going wrong". It made sense before you edited it. – this_is_cat Apr 18 '19 at 19:54
  • @achAmháin It is not an image, It is text. – Ricky Apr 19 '19 at 02:17
  • 1) Use a logical and consistent form of indenting code lines and blocks. The indentation is intended to make the flow of the code easier to follow! Most IDEs have a keyboard shortcut specifically for formatting code. 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). E.G. [This answer](https://stackoverflow.com/a/10862262/418556) hot links to an image embedded in [this question](https://stackoverflow.com/q/10861852/418556). 3) Java GUIs have to work .. – Andrew Thompson Apr 19 '19 at 02:18
  • .. on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 4) **For Swing, we typically use [key bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) rather than the lower level `KeyListener`.** 5) `public class Main extends JFrame { .. //Defining the Frame JFrame f;` .. – Andrew Thompson Apr 19 '19 at 02:18
  • .. don't both extend `JFrame` and declare an instance of one. Use one or the other. In this case, I'd use the latter (the frame that is declared). There is no good reason to extend frame here. – Andrew Thompson Apr 19 '19 at 02:22
  • .. 6) `Scanner d = new Scanner(System.in);` System `in` and a GUI mixes like oil & water mix (they don't). Once a GUI is created, rework the code to take all its input from GUI controls, and to output the result to other GUI controls. Also, give attributes sensible names. `d` could mean anything when you look at it later in the code. – Andrew Thompson Apr 19 '19 at 02:28
  • the scanner doesnt do anything. But I did everything you said like remove stuff and it still wont change anything. – Ricky Apr 19 '19 at 03:16
  • Tip: Add @camickr (or whoever, the `@` is important) to *notify* the person of a new comment. *"I did everything you said.."* Make an [edit] to show us an MCVE / SSCCE using key bindings. The above example will not work without at least one change, but until you have shown an effort to implement key bindings, I won't spend more time on this. – Andrew Thompson Apr 20 '19 at 08:40
  • Oh, by MCVE I mean a [mcve]. – Andrew Thompson Apr 20 '19 at 08:40

1 Answers1

0

As @this_is_cat explained earlier, the listener needs to be on the JFrame and not on the JLabel.

Also, the use of setLayout(null) is not good practice, but was used here because we only have one component with which to work.

package keylistener1;

import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

// Inheriting the JFrame class
public class KeyListener1 extends JFrame {

    private static final String ICON_FILE_PATH = "btn_home.gif";
//    Scanner d = new Scanner(System.in);
    private JLabel label = new JLabel("image not found");
    private JFrame jframe = new JFrame();

    private int xpos = 250;
    private int ypos = 250;

    public KeyListener1() throws HeadlessException {
        initFrame();
    }

    private JFrame initFrame() {

        jframe.setLayout(null);
        jframe.setPreferredSize(new Dimension(525, 525));
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jframe.setVisible(true);
        jframe.setTitle("Key Listener");

        // set up image icon
        Class cls = this.getClass();
        try (InputStream imageSource = cls.getResourceAsStream(ICON_FILE_PATH)) {
            BufferedImage bi = ImageIO.read(imageSource);
            ImageIcon p = new ImageIcon(bi);
            setLabel(new JLabel(p));
            getLabel().setBounds(getXpos(), getYpos(), 50, 50);
        } catch (IOException ex) {
            Logger.getLogger(KeyListener1.class.getName()).log(Level.SEVERE, null, ex);
        }

        initKeyListener();
        jframe.add(getLabel());
        jframe.pack();

        System.out.println("Starting coordinates: " + getXpos() + "," + getYpos());

        return jframe;
    }

    private void initKeyListener() {

        getJframe().addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                System.out.println("jf: " + e.getKeyChar());
                char input = e.getKeyChar();
                if (input == 'w') {
//                    ypos -= 50;
                    setYpos(getYpos() - 50);
                } else if (input == 'a') {
//                    xpos -= 50;
                    setXpos(getXpos() - 50);
                } else if (input == 's') {
//                    ypos += 50;
                    setYpos(getYpos() + 50);
                } else if (input == 'd') {
//                    xpos += 50;
                    setXpos(getXpos() + 50);
                }
                System.out.println("New Coordinates: " + getXpos() + "," + getYpos());

                getLabel().setBounds(getXpos(), getYpos(), 50, 50);
            }
        });
    }

    public JLabel getLabel() {
        return label;
    }

    public void setLabel(JLabel label) {
        this.label = label;
    }

    public int getXpos() {
        return xpos;
    }

    public void setXpos(int xpos) {
        this.xpos = xpos;
    }

    public int getYpos() {
        return ypos;
    }

    public void setYpos(int ypos) {
        this.ypos = ypos;
    }

    public JFrame getJframe() {
        return jframe;
    }

    public void setJframe(JFrame jframe) {
        this.jframe = jframe;
    }

    public static void main(String[] args) {
        new KeyListener1();
    }
}