简体   繁体   English

Swing-将图像添加到GUI

[英]Swing - Adding a image into GUI

So, following from my last post Java Button Width im looking to add some images and set a background color. 因此,从我上一篇文章Java Button Width im开始,我希望添加一些图像并设置背景颜色。 Ive tried a few things, just everytime i do it. 我每次都尝试过一些尝试。 It always gives me errors. 它总是给我错误。

i've tried 我试过了

setBackground(args);

and

img = addImage("image.png");

they dont work for me. 他们不为我工作。 Can somebody give me a hand please? 有人可以帮我吗?

Ok i tried the post made by Disha. 好的,我尝试了Disha发表的帖子。 And the applet still stays the same color, not black 小程序仍然保持不变的颜色,而不是黑色

http://pastebin.com/iijj7fSr http://pastebin.com/iijj7fSr

At the beginning, Please do learn Java Naming Conventions and stick to them. 一开始,请务必学习并遵守Java命名约定

In order for you to provide a background Color to your JFrame , since you had added one JPanel to the CENTER . 为了向JFrame提供背景颜色,因为您已经向CENTER添加了一个JPanel Hence you cannot get one background color by writing : 因此,您无法通过编写以下内容获得一种背景色:

interfaceFrame.setBackground(Color.black);

Now you have to set the opaque property of the JPanel to true and set one Background color for the same like : 现在,您必须将JPanel的opaque属性设置为true,并为以下内容设置一种Background颜色:

setOpaque(true);
setBackground(Color.BLUE);

inside your MenuPane Class's constructor. MenuPane类的构造函数中。

Here here is your modified code : 这是修改后的代码:

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

public class Gmine {
        JFrame interfaceFrame;
        JButton singleplayerButton, multiplayerButton, optionsButton, quitButton;


        public Gmine() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException ex) {
                    } catch (InstantiationException ex) {
                    } catch (IllegalAccessException ex) {
                    } catch (UnsupportedLookAndFeelException ex) {
                    }

                    interfaceFrame = new JFrame("G-Mine");
                    interfaceFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    interfaceFrame.setLayout(new BorderLayout());
                    interfaceFrame.setSize(800,500);
                    //interfaceFrame.setBackground(Color.black);
                    interfaceFrame.add(new MenuPane());
                    interfaceFrame.setLocationRelativeTo(null);
                    interfaceFrame.setVisible(true);
                }
            });
        }

        public class MenuPane extends JPanel {

            public MenuPane() {
                setLayout(new GridBagLayout());

                setOpaque(true);
                setBackground(Color.BLUE);

                singleplayerButton = new JButton("SinglePLayer");
                multiplayerButton = new JButton("MultiPlayer");
                optionsButton = new JButton("Options");
                quitButton = new JButton("Quit");

                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.gridy = 0;
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.ipadx = 20;
                gbc.ipady = 20;

                add(singleplayerButton, gbc);
                gbc.gridy++;
                add(multiplayerButton, gbc);
                gbc.gridy++;
                add(optionsButton, gbc);
                gbc.gridy++;
                add(quitButton, gbc);
            }
        }
        public static void main(String[] args) {
            new Gmine();
        }
}

Now in order to add images to your project you can either see this answer for how to add images to your Project in Java and you can get help from this small sample code as well which is as follows : 现在,为了将图像添加到项目中,您可以看到有关如何在Java中将图像添加到项目中的答案,并且还可以从以下示例代码获得帮助:

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

public class PaintingExample
{
    private CustomPanel contentPane;
    private JTextField userField;
    private JPasswordField passField;
    private JButton loginButton;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Painting Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new CustomPanel();        

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new PaintingExample().displayGUI();
            }
        });
    }
}

class CustomPanel extends JPanel
{
    private BufferedImage image;

    public CustomPanel()
    {
        setOpaque(true);
        setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
        try
        {
            /*
             * Since Images are Application Resources,
             * it's always best to access them in the
             * form of a URL, instead of File, as you are doing.
             * Uncomment this below line and watch this answer
             * of mine, as to HOW TO ADD IMAGES TO THE PROJECT
             * https://stackoverflow.com/a/9866659/1057230
             * In order to access images with getClass().getResource(path)
             * here your Directory structure has to be like this
             *                 Project
             *                    |
             *         ------------------------
             *         |                      |
             *        bin                    src
             *         |                      |
             *     ---------             .java files             
             *     |       |                   
             *  package   image(folder)
             *  ( or              |
             *   .class        404error.jpg
             *   files, if
             *   no package
             *   exists.)
             */
            //image = ImageIO.read(
            //      getClass().getResource(
            //              "/image/404error.jpg"));
            image = ImageIO.read(new URL(
                        "http://gagandeepbali.uk.to/" + 
                                "gaganisonline/images/404error.jpg"));
        }
        catch(IOException ioe)
        {
            System.out.println("Unable to fetch image.");
            ioe.printStackTrace();
        }
    }

    /*
     * Make this one customary habbit,
     * of overriding this method, when
     * you extends a JPanel/JComponent,
     * to define it's Preferred Size.
     * Now in this case we want it to be 
     * as big as the Image itself.
     */
    @Override
    public Dimension getPreferredSize()
    {
        return (new Dimension(image.getWidth(), image.getHeight()));
    }

    /*
     * This is where the actual Painting
     * Code for the JPanel/JComponent
     * goes. Here we will draw the image.
     * Here the first line super.paintComponent(...),
     * means we want the JPanel to be drawn the usual 
     * Java way first, then later on we will
     * add our image to it, by writing the other line,
     * g.drawImage(...).
     */
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

Do uncomment the lines given below and add your image at the specified location : 取消注释下面给出的行,然后将图像添加到指定位置:

image = ImageIO.read(
      getClass().getResource(
              "/image/404error.jpg")); 

If still in doubt, ask any question you might have, I'll try to provide information, if it is within my bounds :-) 如果仍然有疑问,请问您可能有的任何问题,如果可能,我会尽力提供信息:-)

Try this for set background color you use setBackground(Color.color_name); 尝试使用setBackground(Color.color_name);设置背景色setBackground(Color.color_name); and for set image try below code 对于设置图像,请尝试以下代码

Image bgImage= Toolkit.getDefaultToolkit().getImage("wallpaper_adrift.jpg");
contentPane.setBackgroundImage(bgImage);

Also refers to http://www.daniweb.com/software-development/java/threads/346524/how-to-set-background-image-in-java-swing and How to set an image as a background for Frame in Swing GUI of java? 另请参阅http://www.daniweb.com/software-development/java/threads/346524/how-to-set-background-image-in-java-swing如何将图像设置为Frame in的背景Java的Swing GUI?

This is solution you are looking for: 这是您正在寻找的解决方案:

  1. Create a package called like com.icon 创建一个名为com.icon的包

  2. Add your icons to that package (copy/paste) 将您的图标添加到该程序包中(复制/粘贴)

  3. You will add icon on button like this: 您将在按钮上添加图标,如下所示:

     button.setIcon(new ImageIcon(NameOfClass.class.getResource("/com/icon/nameOfIcon.png"))); 

PS Make sure they are in .png format. PS确保它们为.png格式。

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

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