简体   繁体   English

将图像文件添加到JPanel作为背景吗?

[英]Add image file to JPanel as Background?

I use Netbeans IDE and created simple JFrame and filled with a JPanel . 我使用Netbeans IDE并创建了简单的JFrame并填充了一个JPanel Also I added some components to this JPanel (for example: buttons, textfields) 我还向此JPanel添加了一些组件(例如:按钮,文本字段)

I want to add a .jpg file to this JPanel as the background for it. 我想向此JPanel添加.jpg文件作为其背景。 But when I Clean & Build project, this .jpg file must be stored " images/back.jpg " where the Jar file is created. 但是,当我清理并构建项目时,此.jpg文件必须存储在创建Jar文件的“ images/back.jpg ”文件中。

I search over the Net but I can't find any useful examples. 我在网上搜索,但找不到任何有用的示例。 This is my first attempt and any help's appreciated. 这是我的第一次尝试,感谢您的帮助。

public class MainFrame extends javax.swing.JFrame {

    public MainFrame() {
        initComponents();
    }

    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }

    public static void main(String args[]) {

    // ** Look and feel setting code **

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    private javax.swing.JPanel jPanel1;

}

My code as above. 我的代码如上所述。 Only one JFrame filled with JPanel . 只有一个JFrame填充了JPanel

How can I implements below codes to my code? 如何在我的代码中实现以下代码?

This is the code you are looking for, as others have already suggested you need to create a custom component for your JPanel, override the paintComponent() and set the Image as background 这是您正在寻找的代码,因为其他人已经建议您需要为JPanel创建一个自定义组件,覆盖paintComponent()并将Image设置为背景

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class MainFrame extends javax.swing.JFrame {

    private javax.swing.JPanel jPanel1;

    public MainFrame() {
        initComponents();
    }

    private void initComponents() {

        jPanel1 = new ImagePanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
                jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 400,
                Short.MAX_VALUE));
        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 300,
                Short.MAX_VALUE));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
                getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addComponent(
                jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addComponent(
                jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));

        pack();
    }

    public static void main(String args[]) {

        // Look and feel setting code**

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    public class ImagePanel extends JPanel{

        private BufferedImage image;

        public ImagePanel() {
           try {                
              image = ImageIO.read(new File("image name and path"));
           } catch (IOException ex) {
                // handle exception...
           }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters            
        }

    }
}

In Netbeans GUI builder 在Netbeans GUI构建器中

  • Just right click on jPanel1 只需右键单击jPanel1
  • Properties 属性
  • Code
  • Custom Creation Code 自定义创建代码
  • Paste new ImagePanel() 粘贴new ImagePanel()

A little google would have helped. 一个小谷歌会有所帮助。

public class JPanelDemo extends JPanel {
    /**
     * 
     */
     private static final long serialVersionUID = 1L;
     private static final Color BACKGROUND      = Color.black;
     private static final Color BACKGROUND_2    = Color.WHITE;
     String path="/images/back.jpg";

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D graphics = (Graphics2D) g.create();        
        int midY = 100;
        Paint topPaint = new GradientPaint(0, 0, BACKGROUND,0, midY, BACKGROUND_2);
        graphics.setPaint(topPaint);
        graphics.fillRect(0, 0, getWidth(), midY);        
        Paint bottomPaint = new GradientPaint(0, midY + 1, BACKGROUND_2,0, getHeight(), BACKGROUND);
        graphics.setPaint(bottomPaint);
        graphics.fillRect(0, midY, getWidth(), getHeight());
        Image img = new ImageIcon(getClass().getResource(path)).getImage();
        int imgX = img.getWidth(null);
        int imgY = img.getHeight(null);
        graphics.drawImage(img, (getWidth() - imgX) / 2, (getHeight() - imgY) / 2, imgX, imgY, null);
      //  graphics.dispose();
    }
}

Hope it helps :) 希望能帮助到你 :)

Image img = ImageIO.read(new File(*File name*));

protected void paintComponent(Graphics g)
{
   super.paintComponent(g);
   // paint the background image and scale it to fill the entire space
   g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}

Here you go :) JPanel edit- You can set the background in this way. 在这里,您可以:) JPanel编辑-您可以通过这种方式设置背景。 Then build all other components in front of this image. 然后在此图像前面构建所有其他组件。

Check this link. 检查此链接。 http://www.java2s.com/Code/Java/Swing-JFC/Panelwithbackgroundimage.htm http://www.java2s.com/Code/Java/Swing-JFC/Panelwithbackgroundimage.htm

class ImagePanel extends JPanel {

  private Image img;

  public ImagePanel(String img) {
    this(new ImageIcon(img).getImage());
  }

  public ImagePanel(Image img) {
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);
  }

  public void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, null);
  }

}

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

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