0

I have made a student information page using GUI concept. I want to know that how can i add an image at a specific location using JLabel or any other method? What i want is a background image surrounding the whole Jframe and another image at specific location like at the top right. How can i achieve this?

i also found a code to add image using Jlabel but it doesn't work with my code as my setting the layout to null. the code i found

    String path = "Image1.jpg";
    File file = new File(path);
    BufferedImage image = ImageIO.read(file);
    JLabel label = new JLabel(new ImageIcon(image));
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(label);
    f.pack();
    f.setLocation(200,200);
    f.setVisible(true);

Below is my code:

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButton;
import javax.swing.JTextArea; 
import javax.swing.JTextField;

public class LoginPage 
{

JFrame jf;
JLabel gender,hobbies,name_label,rollno_label,marks_label,city_label,address_label;
JTextField name_field,rollno_field,marks_field;
JRadioButton male,female;
ButtonGroup bg;
JCheckBox photography,music,sketching,coding;
JComboBox city_combo;
JTextArea adress_textarea;
JButton save, exit;
JMenuBar mbar;
JMenu file,edit,help;
JMenuItem open,save_item,edit_item,close,cut,copy,paste,find,replace,help_content,about,updates;


    public LoginPage()  //constructor
    {

    jf = new JFrame("Student Information");
    name_label = new JLabel("Student's Name");
    name_field = new JTextField();
    rollno_label = new JLabel("Student's Roll Number");
    rollno_field = new JTextField();
    marks_label = new JLabel("Student's Total Marks Achieved");
    marks_field = new JTextField();
    gender = new JLabel("Gender");
    male = new JRadioButton("Male");
    female = new JRadioButton("Female");
    bg = new ButtonGroup();
    hobbies = new JLabel("Hobbies");
    photography = new JCheckBox("Photography");
    music = new JCheckBox("Music");
    coding = new JCheckBox("Coding");
    sketching = new JCheckBox("Sketching");
    city_label = new JLabel("City");
    city_combo = new JComboBox();
    address_label = new JLabel("Residential Address");
    adress_textarea = new JTextArea();
    save = new JButton("Save");
    exit = new JButton("Exit");
    mbar = new JMenuBar();
    file = new JMenu("File");
    edit = new JMenu("Edit");
    help = new JMenu("Help");
    open = new JMenuItem("open");
    save_item = new JMenuItem("Save");
    edit_item = new JMenuItem("Edit");
    close = new JMenuItem("Close");
    cut = new JMenuItem("Cut");
    copy = new JMenuItem("Copy");
    paste = new JMenuItem("Paste");
    find = new JMenuItem("Find");
    replace = new JMenuItem("Replace");
    about = new JMenuItem("About");
    updates = new JMenuItem("Check for Updates");
    help_content = new JMenuItem("Help Content");

    }

void Display() 
{
    jf.setSize(1000, 700);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setLayout(null);
    jf.getContentPane().setBackground( Color.LIGHT_GRAY );

    name_label.setBounds(50, 50, 150, 20);
    name_field.setBounds(300, 50, 200, 20);
    rollno_label.setBounds(50, 100, 150, 20);
    rollno_field.setBounds(300, 100, 200, 20);
    marks_label.setBounds(50, 150, 200, 20);
    marks_field.setBounds(300, 150, 200, 20);
    gender.setBounds(50, 200, 100, 20);
    male.setBounds(300, 200, 80, 20);
    female.setBounds(400, 200, 80, 20);
    hobbies.setBounds(50, 250, 80, 20);
    photography.setBounds(300, 250, 100, 20);
    music.setBounds(420, 250, 80, 20);
    sketching.setBounds(500, 250, 100, 20);
    coding.setBounds(600, 250, 80, 20);
    city_label.setBounds(50, 300, 100, 20);
    city_combo.setBounds(300, 300, 100, 20);
    address_label.setBounds(50, 350, 200, 20);
    adress_textarea.setBounds(300, 350, 300, 100);
    save.setBounds(300, 500, 100, 50);
    exit.setBounds(600, 500, 100, 50);

    bg.add(male);
    bg.add(female);

    city_combo.addItem("Select City");
    city_combo.addItem("Chandigarh");
    city_combo.addItem("Kurali");
    city_combo.addItem("Mohali");
    city_combo.addItem("Panchkula");

    file.add(open);
    file.add(save_item);
    file.add(edit_item);
    file.add(close);
    edit.add(cut);
    edit.add(copy);
    edit.add(paste);
    edit.add(find);
    edit.add(replace);
    help.add(about);
    help.add(help_content);
    help.add(updates);
    mbar.add(file);
    mbar.add(edit);
    mbar.add(help);

    jf.add(name_label);
    jf.add(name_field);
    jf.add(rollno_label);
    jf.add(rollno_field);
    jf.add(marks_label);
    jf.add(marks_field);
    jf.add(gender);
    jf.add(male);
    jf.add(female);
    jf.add(hobbies);
    jf.add(music);
    jf.add(photography);
    jf.add(sketching);
    jf.add(coding);
    jf.add(city_label);
    jf.add(city_combo);
    jf.add(address_label);
    jf.add(adress_textarea);
    jf.add(save);
    jf.add(exit);

    jf.setJMenuBar(mbar);

    jf.setVisible(true);


}

public static void main(String[] args) {
    new LoginPage().Display();
}

}

2 Answers2

2

What i want is a background image surrounding the whole Jframe

Suggestions:

  • Create a class that extends JPanel,
  • override its paintComponent method
  • be sure to call the super's paintComponent method in your override
  • Draw your background image within this method using g.drawImage(...)
  • Either make this JPanel your JFrame's contentPane or add it to the contentPane BorderLayout.CENTER, and then add your GUI components to this JPanel
  • Make sure that some of the components are not-opaque, e.g., call setOpaque(false) on your JRadioButtons, and perhaps others, so that the background image shows up.

and another image at specific location like at the top right. How can i achieve this?

  • Use the same JPanel above, and draw the smaller image using an overload of drawImage(...) that precisely places the image where you want

Notes:

  • When I create background images for the GUI, I prefer to draw within a JPanel rather than a JLabel since the JLabel is not wired out of the box to act as a contentPane or a decent container.
  • I strongly advise you not to use null layouts and setBounds as this will lead to gui's that might look good on one platform, but not on another, that have JLabels whose text is not fully seen, that are very difficult to upgrade and maintain. Learn and use the layout managers.
  • Looks like you're using multiple JFrames. If so, please read: The Use of Multiple JFrames: Good or Bad Practice?

For example, here's one way to display an image as a background image as well as a smaller image in the right upper portion of the GUI, all within a JPanel:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class LoginPage3 extends JPanel {
    public static final String BG_IMG_PATH = "https://upload.wikimedia.org/wikipedia/"
            + "commons/e/e9/Maesil_%28prunus_mume%29_washed_and_stemmed.jpg";
    public static final String RU_IMG_PATH = "https://upload.wikimedia.org/wikipedia/"
            + "commons/thumb/5/5b/Escudo_de_San_Pedro_de_Atacama.svg/200px-Escudo_de_San_Pedro_de_Atacama.svg.png";

    private BufferedImage backgroundImg;
    private BufferedImage rightUpperImg;

    public LoginPage3(BufferedImage bgImg, BufferedImage ruImg) {
        this.backgroundImg = bgImg;
        this.rightUpperImg = ruImg;
    }

    @Override
    public Dimension getPreferredSize() {
        if (backgroundImg == null || isPreferredSizeSet()) {
            return super.getPreferredSize();
        } else {
            int w = backgroundImg.getWidth();
            int h = backgroundImg.getHeight();
            return new Dimension(w, h);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (backgroundImg != null) {
            g.drawImage(backgroundImg, 0, 0, this);
        }
        if (rightUpperImg != null) {
            int x = getWidth() - rightUpperImg.getWidth();
            g.drawImage(rightUpperImg, x, 0, this);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        BufferedImage bg = null;
        BufferedImage ru = null;
        try {
            bg = ImageIO.read(new URL(BG_IMG_PATH));
            ru = ImageIO.read(new URL(RU_IMG_PATH));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        LoginPage3 mainPanel = new LoginPage3(bg, ru);
        JFrame frame = new JFrame("LoginPage3");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
  • @UsagiMiyamoto: yes, and as I've noted above (and as a answerer on this site, you should also be recommending), he should **not** be using `null` layouts. Since we're leading Swing newbies, we should be recommending best practices, not kludges. – DontKnowMuchBut Getting Better Sep 17 '17 at 13:44
  • I agree that in "normal circumstances" one should not use "null layout", but i personally found that the only possibility when i had to create GUI to a POS terminal, with very low resolution... So i tend to accept that the developer has his/her reasons to use `null` as layout. – Usagi Miyamoto Sep 17 '17 at 13:51
  • @UsagiMiyamoto: but you understand that the reason in this case is that the developer is a newbie and doesn't know any better. – DontKnowMuchBut Getting Better Sep 17 '17 at 13:53
1

For background image:

  • Load it as an icon, and create a JLabel with it. (See your first snippet)
  • Set the JLabel as the JFrame's content pane.

All you have to take care of, that Icon does not stretch, so you have to have an image that is exactly the same size as your JFrame (or larger).

As for the image at a given position, the JLabel creating and Icon loading process is the same, but after adding it to the JFrame you have to set position and size, just like for your other components, EG call setBounds()...

Usagi Miyamoto
  • 6,196
  • 1
  • 19
  • 33