יויו שמוחה
יויו שמוחה

Reputation: 29

Set image background java

I started programming in SWING class recently and I try to set Image (like Space) and on it image(like spaceShip) like background. I would love for you to help me,

Here is my code

public class SpaceWar {

    static JFrame frame = new JFrame("Space War");
    static JPanel panel = new JPanel();

    public static void main(String[] args) {
        
        new SpaceWar();
        
        //frame.setResizable(false);
        frame.setVisible(true);
        
    }
    public SpaceWar() {
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH); 
        Dimension size
        = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setPreferredSize(size);
        frame.setLayout(null);
        panel.setLayout(null);
        panel.setBounds(frame.getPreferredSize().width/4,0,
                frame.getPreferredSize().width/2,frame.getPreferredSize().height);
        frame.add(panel);
        frame.add(new Background());
        spaceShip sp1 = new spaceShip();
        panel.setBackground(Color.black);
        panel.add(sp1);

        System.out.println(panel.getPreferredSize().width);

    }
     
          
}   


class spaceShip extends JLabel{
    
    static ImageIcon img = new ImageIcon("spaceShip.png");

    public spaceShip(){
    
    sizeIcon(100,100,img);
    setIcon(img);
    
    }
    public static ImageIcon sizeIcon(int w,int h,ImageIcon image1){
        
        Image image = image1.getImage(); // transform it 
        Image newimg = image.getScaledInstance(w,h,  java.awt.Image.SCALE_SMOOTH); // scale it the smooth way  
        ImageIcon img1 = new ImageIcon(newimg);  // transform it back
        return img1;    
    }
}
class Background extends JPanel{
    
    public void paint(Graphics g) { // paint() method
          super.paint(g);
          ImageIcon image = new ImageIcon("space.jpg");
          Image bg = image.getImage();
          g.drawImage(bg,0,0,null);
          
    }
}

 

 

Upvotes: 1

Views: 141

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

So, your "core" problem is the use of null layouts and a lack of understand of how components are sized and positioned. Having said that, if your aim is to make a game, this probably isn't the best approach anyway.

Instead, I'd focus on creating a "surface", onto which you can paint all your assets directly, this will give you much greater control.

Start by taking a look at Painting in AWT and Swing and Performing Custom Painting to get a better understanding how the paint system works and how you can work with it to perform custom painting.

I'd also avoid ImageIcon, it's not the best way to handle images, instead, take a look at ImageIO (Reading/Loading an Image), it will generate an IOException if the image can't be loaded and will return a fully realised image (unlike ImageIcon which off loads the image loading to a background thread).

For example...

enter image description here

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JFrame frame = new JFrame();
                    frame.add(new MainPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public class MainPane extends JPanel {

        private BufferedImage ufo;
        private BufferedImage background;

        private int horizontalPosition = 106;

        public MainPane() throws IOException {
            ufo = ImageIO.read(getClass().getResource("/images/ufo.png"));
            background = ImageIO.read(getClass().getResource("/images/starfield.png"));
            System.out.println("background = " + background);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            paintBackground(g2d);
            paintUFO(g2d);
            g2d.dispose();
        }

        protected void paintBackground(Graphics2D g2d) {
            int x = (getWidth() - background.getWidth()) / 2;
            int y = (getHeight() - background.getHeight()) / 2;
            g2d.drawImage(background, x, y, this);
        }

        protected void paintUFO(Graphics2D g2d) {
            int x = (getWidth() - ufo.getWidth()) / 2;
            int y = (getHeight() - ufo.getHeight()) / 2;
            g2d.drawImage(ufo, x, y, this);
        }

    }
}

The example makes use of embedded resources (something to read up on). Managing your assets this way will save you countless hours of wondering why they aren't loading/working. How you achieve this will come down to your IDE and build system, for example, Netbeans and Eclipse will allow you to add resources directly to the src directory, when you're not using maven.

At some point, you're going to want to learn about How to Use Swing Timers and How to Use Key Bindings

Upvotes: 3

Related Questions