如何将图像添加到 GUI,例如横幅?

How do I add an image to GUI such as a banner?

我已经开始学习 Java,我要做的第一件事就是将我所有的 AutoIt 程序转换为 Java。

我尝试转换的第一个程序是我创建的身份验证程序(基本上是社交媒体网站的密码保护程序)。我决定做的第一件事是重新创建 GUI。我已经设法绘制了 JFrame 并更改了背景颜色以匹配 AutoIt gui 的背景颜色。下一步是添加横幅。我很难这样做。我正在寻找一种将图像添加到框架并能够使用像素移动图像的功能。

示例:(请注意,这不是真正的函数。我知道。)

addImageToGUI("myImage.jpg", 45, 35, 250, 500);

这样,我可以通过更改函数参数中的数字来围绕框架导航图像。

下面是我目前的代码。

// Imports
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;


// Class. public class <nameOfFile>
public class GAC extends JPanel {
    // Main class.
    public static void main(String[] args) {
        drawGUI ();
    }
    // Method to create GUI
    public static void drawGUI() {
        // Create a new JFrame and name it 'f'.
        JFrame f = new JFrame("Griffin Account Cracker - Java Edition");
        // Set the size of the new GUI.
        f.setSize(600, 785);
        // I don't know what this does.
        f.add(new GAC());
        // Tell the GUI to exit whenever the 'x' button is pressed.
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        String path = "Images/logo.jpg";
        File file = new File(path);
        BufferedImage image = ImageIO.read(file);
        JLabel label = new JLabel(new ImageIcon(image));
        f.getContentPane().add(label);

        // Make the GUI visible.
        f.setVisible(true);
    }

    // Method to set GUI's background color.
    @Override
public void paint(Graphics f) {

    String guiBanner = "Images/logo.jpg";
    Image guiBannerImg = ImageIO.read(new File(guiBanner));

    f.drawImage(guiBannerImg, 25, 25, null);

    f.setColor(Color.decode("#A0A0A4"));
    f.fillRect(0, 0, this.getWidth(), this.getHeight());
}
}

此外,有人介意告诉我代码的以下部分是做什么的吗?我是 Java.

的新手
f.add(new GAC());

非常感谢任何建议!

f.add(new GAC()) 将面板添加到您的框架。在这种情况下,这不是绝对必要的,但您必须进行一些调整才能将其删除(例如使 class 扩展框架而不是面板)。我将把讨论放在一边。

最简单的方法是在您的绘画方法中绘制横幅。更好的方法可能是创建一个新的自定义 class 扩展面板,将 class 添加到您的框架,然后将这些更改添加到 class 的绘制方法中。我把它留给你 - 无论哪种方式,代码都是相似的。要获取图像:

String myPath = "somepath.gif";
Image myImage = ImageIO.read(new File(myPath));

下一步是绘制该图像,这也发生在 paint() 方法中:

g.drawImage(myImage, xPixel, yPixel, null);

希望对您有所帮助!

编辑:完整代码:

import java.awt.*;
import javax.swing.*;
import java.io.File;
import javax.imageio.ImageIO;

// Class. public class <nameOfFile>
public class GAC extends JPanel {
    // Main class.
    public static void main(String[] args) {
        drawGUI();
    }

    // Method to create GUI
    public static void drawGUI() {
        // Create a new JFrame and name it 'f'.
        JFrame f = new JFrame("Griffin Account Cracker - Java Edition");

        // Set the size of the new GUI.
        f.setPreferredSize(new Dimension(600, 785));

        // add a panel to the frame - the background image will be drawn on the panel
        GAC t = new GAC();
        t.setVisible(true);
        f.add(t);

        // Tell the GUI to exit whenever the 'x' button is pressed.
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Make the GUI visible.
        f.setVisible(true);
        f.pack();
        f.repaint();
    }

    // Method to set GUI's background color.
    @Override
    public void paintComponent(Graphics f) {
        //good practice to call this
        super.paintComponent(f);

        //color the background
        f.setColor(Color.decode("#A0A0A4"));
        f.fillRect(0, 0, this.getWidth(), this.getHeight());

        //we need this try block to handle file reading errors
        try {
            //get the image from a file and scale it to the size you want
            String guiBanner = "Images/Logo.jpg";
            Image guiBannerImg = ImageIO.read(new File(guiBanner)).getScaledInstance(480, 270, Image.SCALE_SMOOTH);

            //draw it at the position you want
            f.drawImage(guiBannerImg, 25, 25, null);
        } catch (Exception e) {
        }
    }
}

有很多简单的方法可以实现这一点,这并不好笑。

例如,您可以使用 JLabel 显示图像并在其上添加另一个 JLabel...

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

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

                try {
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() throws IOException {
            setLayout(new BorderLayout());
            JLabel background = new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("Background.jpg"))));
            JLabel text = new JLabel("Say hello to my little friend");
            text.setFont(text.getFont().deriveFont(Font.BOLD, 24f));
            text.setForeground(Color.WHITE);

            background.setLayout(new GridBagLayout());
            background.add(text);

            add(background);
        }

    }

}

现在,我不喜欢这种方法的问题,例如,如果文本太大,背景标签不会增加大小

因此,您可以只操纵 JLable 的属性并使用它来显示背景图像和文本

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

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

                try {
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() throws IOException {
            setLayout(new BorderLayout());
            JLabel background = new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("Background.jpg"))));
            background.setText("Say hello to my little friend");
            background.setFont(background.getFont().deriveFont(Font.BOLD, 24f));
            background.setForeground(Color.WHITE);

            background.setHorizontalAlignment(JLabel.CENTER);
            background.setVerticalAlignment(JLabel.CENTER);
            background.setHorizontalTextPosition(JLabel.CENTER);
            background.setVerticalTextPosition(JLabel.CENTER);

            add(background);
        }

    }

}

现在,如果你想在未来添加一些额外的功能(锚点位置、比例等),你可以使用自定义组件来绘制背景图像...

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

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

                try {
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() throws IOException {
            setLayout(new BorderLayout());
            BufferedImage background = ImageIO.read(getClass().getResource("Background.jpg"));
            BackgroundPane backgroundPane = new BackgroundPane(background);
            add(backgroundPane);
            backgroundPane.setLayout(new GridBagLayout());

            JLabel text = new JLabel("Say hello to my little friend");
            text.setFont(text.getFont().deriveFont(Font.BOLD, 24f));
            text.setForeground(Color.WHITE);
            backgroundPane.add(text);

            add(backgroundPane);
        }

    }

    public class BackgroundPane extends JPanel {

        private BufferedImage background;

        public BackgroundPane(BufferedImage background) {
            this.background = background;
        }

        @Override
        public Dimension getPreferredSize() {
            return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (background != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                int x = (getWidth() - background.getWidth()) / 2;
                int y = (getHeight() - background.getHeight()) / 2;
                g2d.drawImage(background, x, y,this);
                g2d.dispose();
            }
        }

    }

}

所以,有很多选择

我建议您先看看 How to Use Labels and Laying Out Components Within a Container