0

i wrote this code but when i launch it i can see my background but not the button on it ? please if someone can help me it could be perfect !

package hamza;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class fr {

   public static void main(String[] args){

   JFrame frame = new JFrame("ORDERING FOOD APPLICATION");
   JPanel panel = new JPanel();
   ImageIcon icon = new ImageIcon("hamburger.jpg"); 
   frame.setIconImage(icon.getImage());
   frame.setSize(700, 700);
   frame.setVisible(true);

   try {
      frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("fd12.jpg")))));
   } catch (IOException e) {
      e.printStackTrace();
   }
croxy
  • 4,082
  • 9
  • 28
  • 46

2 Answers2

2
  1. Don't make the frame visible until you've finished setting up the UI
  2. Prefer pack over setSize
  3. JLabel does not have a layout manager by default, so you will need to supply one
  4. JLabel will NOT calculate it's preferred layout size based on it's child components (it will ignore the layout manager), it only uses the icon and text properties, so beware of that.

Click me

JFrame frame = new JFrame("ORDERING FOOD APPLICATION");
JPanel panel = new JPanel();
ImageIcon icon = new ImageIcon("hamburger.jpg");
frame.setIconImage(icon.getImage());

try {
    frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("fd12.jpg")))));
} catch (IOException e) {
    e.printStackTrace();
}
frame.setLayout(new GridBagLayout());
JButton btn = new JButton("Click me");
frame.add(btn);
frame.pack();
frame.setVisible(true);

See this for an alternative to using a JLabel which may be more flexible

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

You did't add button on frame, try code below

JButton button = new JButton("Click Me");
frame.add(button);
Raza Ali Poonja
  • 1,086
  • 8
  • 16