简体   繁体   English

Jframe.Jbutton与背景

[英]Jframe.Jbutton with background

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();
   }
  1. Don't make the frame visible until you've finished setting up the UI 完成设置UI之前,不要使框架可见
  2. Prefer pack over setSize setSize喜欢pack
  3. JLabel does not have a layout manager by default, so you will need to supply one JLabel默认情况下没有布局管理器,因此您需要提供一个
  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. JLabel不会基于其子组件来计算其首选的布局大小(它将忽略布局管理器),它仅使用icontext属性,因此请注意。

点击我

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 请参阅此内容以替代使用JLabel ,它可能更灵活

You did't add button on frame, try code below 您没有在框架上添加按钮,请尝试以下代码

JButton button = new JButton("Click Me");
frame.add(button);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM