Hi, I am pretty sure there is a more effective way of achieving this. Would love for some input from you guys.

Basically, I have a class called GamePanel and it contains this:

SpaceShip spaceship = new SpaceShip("Galatar");

public void paintComponent(Graphics g) {
       Graphics2D g2d = (Graphics2D) g;
       g2d.drawImage(bgI,0,0,null);
       g2d.drawImage(spaceship.setSpaceShipSprite(""),sShipX,sShipY,null);
  
    }
//KeyPressed method
if(e.getKeyCode()==KeyEvent.VK_LEFT){
          sShipX = spaceship.move_left(sShipX);
          spaceship.setSpaceShipSprite("left");
       
        if(e.getKeyCode()==KeyEvent.VK_RIGHT){
          sShipX = spaceship.move_right(sShipX);
          spaceship.setSpaceShipSprite("right");
       }

getSpaceShipSprite() and setSpaceShipSprite() call methods in my SpaceShip class as follows:

public Image setSpaceShipSprite(String i)
        {
             if(i.equals("right")){
                img = new ImageIcon("src\\resources\\spaceShipR.png").getImage();
            }
             else if(i.equals("left")){
           img = new ImageIcon("src\\resources\\spaceShipL.png").getImage();
             }
        else
            return img;
            return img;
        }

I don't know why, but this seems like a sloppy way to do things, I could be over thinking this which is one of my main problems(haha) but any input would be appreciated.

EDIT: the getSpaceShipSprite() method is used once to get a starting image

method get() load images from files to Image[] array - used once
method set() gets images from Image[] array - used many times

Show your getSpaceShipSprite() method.

method get() load images from files to Image[] array - used once
method set() gets images from Image[] array - used many times

Show your getSpaceShipSprite() method.

I have actually removed the getSpaceShipSprite() method now.
I am not using any arrays, This is a very basic 'test' program, I am only changing between 2 images.

Are you a bot or something? Or just incapable of reading?

Thanks for your time anyway.

I'm a man from the Earth.
More effective way (part 2)

public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(bgI, 0, 0, null);
        spaceship.drawShip(g2d);
    }

    //KeyPressed method
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            spaceship.move_left();
        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            spaceship.move_right();
        }

let the captain of Galatar spaceship do it.

thanks, I had already thought of that but wasn't sure it would work!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.