0

I've started learning Java and the first thing I'm trying to do is convert all of my AutoIt programs to 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. I've already managed to draw a JFrame and change the background color to match that of the 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.

f.add(new GAC());

Any suggestions is greatly appreciated!

Timothy Bomer
  • 504
  • 5
  • 21
  • *"I've started learning Java.."* Start with command line apps. GUIs are quite advanced (when the GUI has to work across platforms). *"The next step would be to add the banner."* Sounds like futzing to me. Get the basics of the toolkit sorted before worrying about window trimmings. *"Any suggestions is greatly appreciated!"* Return to the basics & when you get back to GUIs, avoid trying to make 'picture perfect' replications of other apps. Users want an app. that works, not glitz. – Andrew Thompson Apr 09 '16 at 01:09
  • `public class GAC extends JPanel { .. public void paint(Graphics f) { f.setColor(Color.decode("#A0A0A4")); ..` 1) Given this is a `JComponent` we should override the `paintComponent(Graphics)` method. 2) When overriding any paint method, a call to the super method should be the first thing done. So more like `public class GAC extends JPanel { .. public void paintComponent(Graphics f) { super.paintComponent(f); f.setColor(Color.decode("#A0A0A4")); ..` – Andrew Thompson Apr 09 '16 at 01:13
  • `f.drawImage(guiBannerImg, 25, 25, null);` should best be `f.drawImage(guiBannerImg, 25, 25, this); // every JComponent IS AN ImageObserver!` – Andrew Thompson Apr 09 '16 at 01:15
  • I apologize for my Java-Based ignorance haha. I'm am trying to replicate a simple application I wrote in AutoIt. Given the similarities between the languages, I figured it wouldn't be too bad. – Timothy Bomer Apr 09 '16 at 01:18
  • [How to Use Labels](http://docs.oracle.com/javase/tutorial/uiswing/components/label.html)? – MadProgrammer Apr 09 '16 at 02:01

2 Answers2

2

f.add(new GAC()) adds a panel to your frame. 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. 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:

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) {
        }
    }
}
nhouser9
  • 6,730
  • 3
  • 21
  • 42
  • 1
    Thank you for your quick response! I'm getting this error, "GAC.java:30: error: cannot find symbol f.drawImage(guiBannerImg, 25, 25, null); ^ symbol: method drawImage(Image,int,int,) location: variable f of type JFrame 1 error" I've amended my code to show what I've done. – Timothy Bomer Apr 09 '16 at 01:13
  • @TimothyBomer I tried it in my editor - I had to wrap my file operations in try{}catch blocks to handle exceptions, but other than that it compiled and ran. – nhouser9 Apr 09 '16 at 01:19
  • @TimothyBomer Make sure you have the right imports too. – nhouser9 Apr 09 '16 at 01:20
  • Are my imports wrong? I apologize, I am still VERY new to Java. I'm also not using Eclipse or NetBeans. I am using Notepad++ with a Java compiler – Timothy Bomer Apr 09 '16 at 01:29
  • @TimothyBomer It compiles for me with these: import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.*; import java.io.File; import javax.imageio.ImageIO; – nhouser9 Apr 09 '16 at 01:37
  • It's compiling but the image isn't showing. It's giving me an error. "GAC.java:42: error: cannot find symbol f.drawImage(guiBannerImg, 25, 25, null); ^ symbol: variable guiBannerImg location: class GAC 1 error – Timothy Bomer Apr 09 '16 at 01:38
  • @TimothyBomer So i am running it myself now and noticed several things. See my updated answer that I'm posting now. – nhouser9 Apr 09 '16 at 01:45
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/108679/discussion-between-timothy-bomer-and-nhouser9). – Timothy Bomer Apr 09 '16 at 01:49
  • 1
    You should be calling `super.paintCo,ponent` – MadProgrammer Apr 09 '16 at 02:00
2

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...

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

    }

}

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

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

    }

}

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...

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

    }

}

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366