Alek345 Alek345 - 4 months ago 18
Java Question

JLabel as Background Image

I can't seem to figure this out.

Please help I need this to work out to continue my project.

Awww I have to add this for allowing me to post

import javax.swing.*;
import java.awt.*;

@SuppressWarnings("serial")
public class MainFrame extends JFrame {


public static void Draw(){
DrawFrame();
}


public static void DrawFrame(){
int h = 600;
int w = 340;
JFrame frame = new JFrame();
JLabel background1 = new JLabel(new ImageIcon("/res/mariocraft_main.png"));


frame.setResizable(false);
frame.setSize(h, w);
frame.setTitle("MarioCraft");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(background1);

background1.setVisible(true);
background1.setIcon(new ImageIcon("/res/mariocraft_main.png"));
background1.setText("Background failed to load");

}

}

Answer

A JLabel always displays the image at its actual size so you should not be manually setting the size of the frame.

Instead the code should be something like:

JLabel background1 = new JLabel(new ImageIcon("/res/mariocraft_main.png"));

JFrame frame = new JFrame();     
frame.add(background1); 
frame.pack();
frame.setResizable(false);     
frame.setVisible(true);     
Comments