简体   繁体   English

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

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

I've started learning Java and the first thing I'm trying to do is convert all of my AutoIt programs to Java. 我已经开始学习Java,而我要做的第一件事就是将所有AutoIt程序都转换为Java。

The first program I'm trying to convert is an authentication program I created (basically a password protection program for social media sites). 我要转换的第一个程序是我创建的身份验证程序(基本上是社交媒体网站的密码保护程序)。 The first thing I decided to do was recreate the GUI. 我决定要做的第一件事是重新创建GUI。 I've already managed to draw a JFrame and change the background color to match that of the AutoIt gui. 我已经设法绘制一个JFrame并更改背景颜色以匹配AutoIt gui的背景颜色。 The next step would be to add the banner. 下一步将是添加横幅。 I'm having trouble doing so. 我这样做很麻烦。 I'm looking for a function to add an image to the frame and be able to move it around using pixels. 我正在寻找一种将图像添加到框架并能够使用像素移动图像的功能。

Example: (Note, this is not a real function.. That I'm aware of.) 示例:(请注意,这不是一个真正的函数。我知道。)

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

That way, I could navigate the image around the frame simply by changing the numbers in the functions parameters. 这样,我可以简单地通过更改功能参数中的数字来浏览图像。

Below is the code I have so far. 下面是我到目前为止的代码。

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

Also, would anybody mind telling me what the below part of my code does? 另外,有人会告诉我我代码的以下部分做什么吗? I'm very new to Java. 我是Java的新手。

f.add(new GAC());

Any suggestions is greatly appreciated! 任何建议,不胜感激!

f.add(new GAC()) adds a panel to your frame. f.add(new GAC())将面板添加到框架。 It is not strictly necessary in this case, but you would have to do some tweaks to remove it (like making your class extend frame instead of panel). 在这种情况下,这不是绝对必要的,但是您必须做一些调整才能将其删除(例如,使类扩展为框架而不是面板)。 I will leave that discussion aside. 我将把讨论放在一边。

The easiest way to do this is to just draw the banner within your paint method. 最简单的方法是在绘制方法中绘制横幅。 A better way might be to create a new custom class extending panel, add that class to your frame, and add these changes in the paint method of that class. 更好的方法可能是创建一个新的自定义类扩展面板,将该类添加到您的框架中,然后在该类的paint方法中添加这些更改。 I leave it to you - either way, the code is similar. 我把它留给您-无论哪种方式,代码都是相似的。 To get an image: 要获取图像:

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

The next step is to paint that image, which also happens in the paint() method: 下一步是绘制该图像,这也发生在paint()方法中:

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

Hope this helps! 希望这可以帮助!

Edit: Full code: 编辑:完整代码:

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) {
        }
    }
}

There are simple so many ways you might be able to achieve this it's not funny. 有许多简单的方法可以实现此目标,这并不好笑。

For example, you could use a JLabel to show the image and add another JLabel ontop of it... 例如,您可以使用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);
        }

    }

}

Now, there are issues with this approach that I don't like, for example, if the text is too large, the background label won't increase in size 现在,我不喜欢这种方法的问题,例如,如果文本太大,则背景标签的大小不会增加

So, instead, you could just manipulate the properties of the JLable and use it to display the background image and text 因此,相反,您可以操纵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);
        }

    }

}

Now, if you want to add some additional functionality in the future (anchor position, scale, etc), you could use a custom component for painting the background image... 现在,如果您想在将来添加一些其他功能(锚定位置,比例等),则可以使用自定义组件来绘制背景图像...

背景窗格

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

    }

}

So, lots of options 所以,很多选择

I'd encourage you to have a look at How to Use Labels and Laying Out Components Within a Container for starters 我鼓励您看一下如何使用标签以及如何 在容器中布置组件以供初学者使用

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

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