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

时间:2016-04-09 00:59:17

标签: java image swing user-interface autoit

我开始学习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());

非常感谢任何建议!

2 个答案:

答案 0 :(得分:2)

f.add(new GAC())为您的框架添加一个面板。在这种情况下,它并不是绝对必要的,但你必须做一些调整才能删除它(比如让你的类扩展框架而不是面板)。我将把讨论放在一边。

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

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

答案 1 :(得分:2)

你可以通过简单的方法实现这一点,这并不好笑。

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

Label

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的属性并使用它来显示背景图像和文本

Label it up

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

    }

}

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

Background Pane

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 LabelsLaying Out Components Within a Container作为初学者