JComponents not showing up with picture background?
Asked Answered
B

2

5

My components are not showing up. How do I fix this?

Code:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

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

public class login implements ActionListener{
    JTextField gusername;
    JTextField gpassword;
    static String username;
    static String password;

    void logini() throws IOException {
        JFrame window = new JFrame("Login");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(300, 250);
        window.setResizable(false);
        window.setVisible(true);

        JPanel mainp = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        window.add(mainp);

        BufferedImage myPicture = ImageIO.read(new File("c:\\bgd.png"));
        JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
        mainp.add(picLabel, c);

        c.gridx = 0;
        c.gridy = 1;
        gusername = new JTextField();
        gusername.setText("Username");
        mainp.add(gusername, c);

        c.gridx = 0;
        c.gridy = 2;
        gpassword = new JTextField();
        gpassword.setText(" password ");
        mainp.add(gpassword, c);

        c.gridx = 0;
        c.gridy = 3;
        JButton login = new JButton("Login");
        mainp.add(login, c);

        login.addActionListener(this);
        login.setActionCommand("ok");
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equalsIgnoreCase("ok")){
            try {
                this.username = (gusername.getText());
                this.password = (gpassword.getText());
                System.out.println("0");
            }
            catch(NumberFormatException ex){
                System.out.println("ERROR: Could not preform function: 7424");
            }
        }
    }
}

Result:

Britnibrito answered 6/7, 2012 at 20:22 Comment(5)
The way you writing your code is questionable. Never call setVisible(true), until the JFrame's size has been realized. Mean to say, add your components to your Jframe then call setVsibile(). Please have a look at this related exampleAnnora
@nIcE cOw Ok It worked, now all the objects are not on the picture but written lower on the Frame.Eugeniaeugenics
Since you adding your components to the JPanel, and the picture is on a JLabel. So what you can do is, either draw the image on the JPanel as described in the above example shown by me, or else you can add your components to the JLabel by setting it's Layout as described in this example. +1 for atleast showing the code that you are using, though it's not even closer for being a valid SSCCEAnnora
@nIcE cOw I don't understand the examples, mainly because I don't understand the concept of what is doing what. :/Eugeniaeugenics
Sorry for the late reply, that was night time, when you send this message :( Let me add a small example for you, I will go step by step, to explain the whole thing.Annora
A
7

Here first watch this small example, do let me know if you understood what is going on in here. Then only we will go a step further, slowly slowly. Try to go through this example, in which I am showing you how to draw on a JPanel

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

public class PaintingExample {

    private CustomPanel contentPane;

    private void displayGUI() {
        JFrame frame = new JFrame("Painting Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        contentPane = new CustomPanel();        

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new PaintingExample().displayGUI();
            }
        });
    }
}

class CustomPanel extends JPanel {

    private BufferedImage image;

    public CustomPanel() {
        setOpaque(true);
        setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
        try {
            /*
             * Since Images are Application Resources,
             * it's always best to access them in the
             * form of a URL, instead of File, as you are doing.
             * Uncomment this below line and watch this answer
             * of mine, as to HOW TO ADD IMAGES TO THE PROJECT
             * https://mcmap.net/q/279686/-loading-resources-like-images-while-running-project-distributed-as-jar-archive
             * In order to access images with getClass().getResource(path)
             * here your Directory structure has to be like this
             *                 Project
             *                    |
             *         ------------------------
             *         |                      |
             *        bin                    src
             *         |                      |
             *     ---------             .java files             
             *     |       |                   
             *  package   image(folder)
             *  ( or              |
             *   .class        404error.jpg
             *   files, if
             *   no package
             *   exists.)
             */
            //image = ImageIO.read(
            //      getClass().getResource(
            //              "/image/404error.jpg"));
            image = ImageIO.read(new URL(
                        "http://i.imgur.com/8zgHpH8.jpg"));
        } catch(IOException ioe) {
            System.out.println("Unable to fetch image.");
            ioe.printStackTrace();
        }
    }

    /*
     * Make this one customary habbit,
     * of overriding this method, when
     * you extends a JPanel/JComponent,
     * to define it's Preferred Size.
     * Now in this case we want it to be 
     * as big as the Image itself.
     */
    @Override
    public Dimension getPreferredSize() {
        return (new Dimension(image.getWidth(), image.getHeight()));
    }

    /*
     * This is where the actual Painting
     * Code for the JPanel/JComponent
     * goes. Here we will draw the image.
     * Here the first line super.paintComponent(...),
     * means we want the JPanel to be drawn the usual 
     * Java way first (this usually depends on the opaque
     * property of the said JComponent, if it's true, then
     * it becomes the responsibility on the part of the
     * programmer to fill the content area with a fully
     * opaque color. If it is false, then the programmer
     * is free to leave it untouched. So in order to 
     * overcome the hassle assoicated with this contract,
     * super.paintComponent(g) is used, since it adheres
     * to the rules, and performs the same task, depending
     * upon whether the opaque property is true or false),
     * then later on we will add our image to it, by 
     * writing the other line, g.drawImage(...).
     */
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

Compile and Run:

  1. Start command prompt/terminal/cmd. And move to the location referred to by the Project folder
  2. Now compile the code by using:

    C:\Project>javac -d bin src\*.java
  3. Now move to bin folder, by issuing command:

    C:\Project>cd bin
  4. Once inside bin folder, issue the following command to run:

    C:\Project\bin>java PaintingExample

Here is the code when using JLabel as the base for the image :

import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;

public class LabelExample {

    private JPanel contentPane;
    private JLabel imageLabel;

    private void displayGUI() {
        JFrame frame = new JFrame("Label Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        contentPane = new JPanel();
        contentPane.setOpaque(true);
        contentPane.setBorder(
                BorderFactory.createLineBorder(Color.BLACK, 5));
        //imageLabel = new JLabel(
        //          new ImageIcon(
        //              getClass().getResource(
        //                  "/image/404error.jpg")));
        try {
            imageLabel = new JLabel(new ImageIcon(
                    new URL("http://i.imgur.com/8zgHpH8.jpg")));
        } catch(MalformedURLException mue) {
            System.out.println(
                    "Unable to get Image from"
                        + "the Resource specified.");
            mue.printStackTrace();
        }
        contentPane.add(imageLabel);
        frame.setContentPane(contentPane);  
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LabelExample().displayGUI();
            }
        });
    }
}

Here is the output of both the above codes :

404Error

Annora answered 7/7, 2012 at 4:54 Comment(1)
@TimothyO'Connell : Please do let me know, if there is something more you want to know on the whole thingy :-)Annora
C
0
window.setVisible(true); should be invoked only after all the components have been added to the frame.
 void logini() throws IOException {
        JFrame window = new JFrame("Login");
        JPanel mainp = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        window.add(mainp);

        BufferedImage myPicture = ImageIO.read(new File("c:\\bgd.png"));
        JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
        mainp.add(picLabel, c);

        c.gridx = 0;
        c.gridy = 1;
        gusername = new JTextField();
        gusername.setText("Username");
        mainp.add(gusername, c);

        c.gridx = 0;
        c.gridy = 2;
        gpassword = new JTextField();
        gpassword.setText(" password ");
        mainp.add(gpassword, c);

        c.gridx = 0;
        c.gridy = 3;
        JButton login = new JButton("Login");
        mainp.add(login, c);

        login.addActionListener(this);
        login.setActionCommand("ok");

        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(500, 250);
        window.setResizable(false);
        window.setVisible(true);
    }
Cyclops answered 25/2, 2016 at 12:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.