2

因此,在我上一篇文章Java Button Width之后,我希望添加一些图像并设置背景颜色。我尝试了一些东西,只是每次我都这样做。它总是给我错误。

我试过了

setBackground(args);

img = addImage("image.png");

他们不为我工作。有人可以帮帮我吗?

好的,我尝试了 Disha 的帖子。而且小程序仍然保持相同的颜色,而不是黑色

http://pastebin.com/iijj7fSr

4

3 回答 3

5

一开始,请务必学习Java 命名约定并坚持下去。

为了让您为您的 提供背景颜色JFrame,因为您已经添加了一个JPanelCENTER. 因此,您无法通过编写获得一种背景颜色:

interfaceFrame.setBackground(Color.black);

现在您必须将 opaque 的属性设置JPanel 为 true 并为相同的设置一种背景颜色:

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

MenuPane 类的构造函数中。

这是您修改后的代码:

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();
        }
}

现在,为了将图像添加到您的项目,您可以查看如何在 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);
    }
}

请取消注释下面给出的行并将您的图像添加到指定位置:

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

如果仍有疑问,请提出您可能有的任何问题,如果在我的范围内,我会尽力提供信息:-)

于 2012-11-02T13:57:03.983 回答
2

试试这个设置你使用的背景颜色setBackground(Color.color_name);和设置图像试试下面的代码

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

也可以参考http://www.daniweb.com/software-development/java/threads/346524/how-to-set-background-image-in-java-swingHow to set an image as background for Frame in java的Swing GUI?

于 2012-11-02T11:27:56.617 回答
1

这是您正在寻找的解决方案:

  1. 创建一个名为like的包com.icon

  2. 将您的图标添加到该包(复制/粘贴)

  3. 您将在按钮上添加图标,如下所示:

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

PS 确保它们是 .png 格式。

于 2012-11-02T11:08:16.990 回答