【问题标题】:Background image in javajava中的背景图片
【发布时间】:2011-02-11 23:01:23
【问题描述】:

我正在尝试在 java 中将图像作为我的界面的背景,我尝试编写一个执行此操作的类并使用它,但有没有更简单的方法来做到这一点。

这是我使用的code

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class BackgroundImagePanelExample {

    // Set up contraints so that the user supplied component and the
    // background image label overlap and resize identically
    private static final GridBagConstraints gbc;

    static {
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.NORTHWEST;
    }

    /**
     * Wraps a Swing JComponent in a background image. Simply invokes the overloded
     * variant with Top/Leading alignment for background image.
     *
     * @param component - to wrap in the a background image
     * @param backgroundIcon - the background image (Icon)
     * @return the wrapping JPanel
     */
    public static JPanel wrapInBackgroundImage(JComponent component,
        Icon backgroundIcon) {
        return wrapInBackgroundImage(
            component,
            backgroundIcon,
            JLabel.TOP,
            JLabel.LEADING);
    }

    /**
     * Wraps a Swing JComponent in a background image. The vertical and horizontal
     * alignment of background image can be specified using the alignment
     * contants from JLabel.
     *
     * @param component - to wrap in the a background image
     * @param backgroundIcon - the background image (Icon)
     * @param verticalAlignment - vertical alignment. See contants in JLabel.
     * @param horizontalAlignment - horizontal alignment. See contants in JLabel.
     * @return the wrapping JPanel
     */
    public static JPanel wrapInBackgroundImage(JComponent component,
        Icon backgroundIcon,
        int verticalAlignment,
        int horizontalAlignment) {

        // make the passed in swing component transparent
        component.setOpaque(false);

        // create wrapper JPanel
        JPanel backgroundPanel = new JPanel(new GridBagLayout());

        // add the passed in swing component first to ensure that it is in front
        backgroundPanel.add(component, gbc);

        // create a label to paint the background image
        JLabel backgroundImage = new JLabel(backgroundIcon);

        // set minimum and preferred sizes so that the size of the image
        // does not affect the layout size
        backgroundImage.setPreferredSize(new Dimension(1, 1));
        backgroundImage.setMinimumSize(new Dimension(1, 1));

        // align the image as specified.
        backgroundImage.setVerticalAlignment(verticalAlignment);
        backgroundImage.setHorizontalAlignment(horizontalAlignment);

        // add the background label
        backgroundPanel.add(backgroundImage, gbc);

        // return the wrapper
        return backgroundPanel;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Background Image Panel Example");

        // Create some GUI
        JPanel foregroundPanel = new JPanel(new BorderLayout(10, 10));
        foregroundPanel.setBorder(
            BorderFactory.createEmptyBorder(10, 10, 10, 10));
        foregroundPanel.setOpaque(false);

        foregroundPanel.add(new JLabel("Comment:"), BorderLayout.NORTH);
        foregroundPanel.add(new JScrollPane(new JTextArea(3, 10)),
            BorderLayout.CENTER);
        foregroundPanel.add(
            new JLabel(
            "Please enter your comments in text box above."
            + " HTML syntax is allowed."), BorderLayout.SOUTH);

        frame.setContentPane(wrapInBackgroundImage(foregroundPanel,
            new ImageIcon(
            BackgroundImagePanelExample.class.getResource("backgd.jpg"))));

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

谢谢

【问题讨论】:

  • 这个“界面:”你说的是桌面应用程序,GUI 是在 Swing 中实现的吗?还是其他选择?
  • 只是一个在 Swing 中实现的 GUI
  • 如果您不向我们展示您的一些代码,我们怎么知道是否有更简单的方法?
  • 重新格式化和引用;如果不正确,请恢复。

标签: java user-interface image swing background


【解决方案1】:

我猜你收到的是java.lang.NullPointerException,因为getResource() 找不到backgd.jpg。您也许可以将图像文件放在源文件旁边并重建项目。或者,您可以在整理内容时从文件系统加载它作为临时措施。

frame.setContentPane(wrapInBackgroundImage(
    foregroundPanel, new ImageIcon("image.jpg")));

【讨论】:

    【解决方案2】:

    我实际上不明白你在问什么。如果您要问,是否有更简单的方法来构建 Swing 应用程序 - 答案是肯定的。将 NetBeans IDE 与 Swing builder 一起使用,它可以生成非常合理的生成代码,并允许您编辑大量组件。与从 NetBeans 生成的代码相比,手写的 Swing 更容易“损坏”,而且更耗时...

    【讨论】:

      【解决方案3】:
      import java.awt.Dimension;
      import java.awt.Graphics;
      import java.awt.Image;
      
      import javax.swing.ImageIcon;
      import javax.swing.JFrame;
      import javax.swing.JPanel;
      
      public class ImageTest {
      
        public static void main(String[] args) {
          ImagePanel panel = new ImagePanel(new ImageIcon("images/background.png").getImage());
      
          JFrame frame = new JFrame();
          frame.getContentPane().add(panel);
          frame.pack();
          frame.setVisible(true);
        }
      }
      
      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);
        }
      
      }
      

      【讨论】:

        【解决方案4】:
        public class BackgroundPanel extends JPanel {
        
        private static final long serialVersionUID = 1L;
        Image image;
        
        public BackgroundPanel() {
            super();
            initialize();
        }
        
        /**
         * This method initializes this
         * 
         * @return void
         */
        private void initialize() {
            try {
                image = new ImageIcon(getClass().getResource("background.jpg")).getImage();
            } catch (Exception e) {
                /*handled in paintComponent()*/
            }
            this.setSize(800, 470);
            this.setLayout(null);
        }
        
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); 
            if(image != null) {
                g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
            }
        }
        }
        

        【讨论】:

          猜你喜欢
          • 2011-01-14
          • 2014-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-16
          • 1970-01-01
          相关资源
          最近更新 更多