views:

302

answers:

2

I'm using the Netbeans GUI builder, but it's a little confusing now. How can I add an image to a panel? I think i'm doing it correct, but it's not showing up. I think it should be in the init() method, but netbeans does not allow me to change that part of the code. This is the code I added for the image:

  //these four lines I added to add the image
        imageIcon = new ImageIcon("login_icon.png");
        image = new JLabel(imageIcon);
        image.setToolTipText("SGS Security");
        topPanel.add(image);

My Class starts here:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * Created on Oct 27, 2009, 8:34:15 PM
 */

package sgs;

import javax.swing.ImageIcon;
import javax.swing.JLabel;


public class Login extends javax.swing.JFrame {

    JLabel image;
    ImageIcon imageIcon;

    /** Creates new form Login */
    public Login() {
        initComponents();

  //these four lines I added to add the image
        imageIcon = new ImageIcon("login_icon.png");
        image = new JLabel(imageIcon);
        image.setToolTipText("SGS Security");
        topPanel.add(image);
    }



    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        topPanel = new javax.swing.JPanel();
        userLabel = new javax.swing.JLabel();
        passwordLabel = new javax.swing.JLabel();
        connectLabel = new javax.swing.JLabel();
        forgotPassLabel = new javax.swing.JLabel();
        forgotPassCheckBox = new javax.swing.JCheckBox();
        cancelButton = new javax.swing.JButton();
        okButton = new javax.swing.JButton();
        passwordTextField = new javax.swing.JTextField();
        userTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(216, 156, 60));

        topPanel.setBackground(new java.awt.Color(28, 90, 198));

        javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
        topPanel.setLayout(topPanelLayout);
        topPanelLayout.setHorizontalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 406, Short.MAX_VALUE)
        );
        topPanelLayout.setVerticalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 71, Short.MAX_VALUE)
        );

        userLabel.setText("User name:");

        passwordLabel.setText("Password:");

        connectLabel.setText("Connect to SGS");

        forgotPassLabel.setText("Forgot password");

        forgotPassCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                forgotPassCheckBoxActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        userTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                userTextFieldActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(connectLabel)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(passwordLabel)
                        .addComponent(userLabel)))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(userTextField)
                    .addComponent(passwordTextField)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(forgotPassCheckBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(forgotPassLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(connectLabel)
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userLabel)
                    .addComponent(userTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordLabel)
                    .addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(forgotPassLabel)
                    .addComponent(forgotPassCheckBox))
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void forgotPassCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void userTextFieldActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel connectLabel;
    private javax.swing.JCheckBox forgotPassCheckBox;
    private javax.swing.JLabel forgotPassLabel;
    private javax.swing.JButton okButton;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JTextField passwordTextField;
    private javax.swing.JPanel topPanel;
    private javax.swing.JLabel userLabel;
    private javax.swing.JTextField userTextField;
    // End of variables declaration

}
A: 

This is one of the weird behaviors in Java (GUIs). You can manually paint the image on a panel.

Here is what I use:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2= (Graphics2D) g;

    if (currentImage != null) {
        g2.drawImage(currentImage, null, 0, 0);
    } 
}

Also you should create a "ImagePanel" component, which is an JPanel that encapsolates the Image.

The middle arguement for drawImage is null, because I do not intend on performing an image operation on it.

monksy
-1, You do not have to manually paint the image on a panel. Read the Swing tutorial on "How to Use Labels" or "How to Use Icons" for working examples. The only time you would use custom painting is if you need to modify the image by scaling or some other feature.
camickr
It works. If you have an alternative answer, don't downvote an answer that works. Add your own.
monksy
Lots of things work, but it is unnecessary to create a custom class (and reinvent the wheel) to do this, when support for images is part of the API and well documented. However I don't vote suggestions down just because I may not agree with the suggestion. The reason I down voted it was because your intial statement was factually wrong.
camickr
According to your logic, that either it being one of the "weird behaviors" or being able to manually paint it to the panel is factually incorrect?
monksy
JLabels with an icon work all over the place. I think maybe we should probably help figure out why code that should work easily isn't working in the original poster's particular case rather than having him reinvent a component that already exists. But I'm not voting this up or down. Suffice it to say that I've used JLabel to paint images literally hundreds of times.
PSpeed
"You have to manually paint " is wrong. You can paint it manually if you want, but you don't have to do this. look the 1st example at http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html
Nettogrof
+1  A: 

Ditch the GUI builder and learn how to create GUIs on your own. That way you spend time learning Java instead of learning an IDE. There is probably some GroupLayout property that is not properly set and since GroupLayout was designed to be used by IDEs and not humans I have no idea what the problem might be.

The other possibility is that the IDE can't find your image. Did you add a System.out.println to diplay the image and make sure its not null.

I suggest you read the section from the Swing tutorial on How to Use Icons for a working example that you can download and test to see if it works. Just replace the icons in the tutorial with your icons to make sure they are found.

Edit:

After having a second look at the code I believe my original suggestion is correct. You attempt to add the label to the panel using a single line of code:

topPanel.add(image);

Look at the code generated by the IDE. The add statements are NOT that simple. If you want to manually add a component after the fact then you need read the section from the tutorial on "How to Use Group Layout" to understand the various constraints and methods used.

Or you need to figure out how to do it in the IDE. Thats why I prefer the do it yourself approach. Then you are responsible for the code, not the IDE.

camickr
At least I had the curtesy to explain why I down voted the other answer. The people in this forum amaze me. Again, nothing in my answer is factually wrong, if it is then let me know what?
camickr
That wasn't me. Your solution works.
monksy
(just upvoted to reset the vote to 0)
monksy
+1 for learing IDE vs learning Java
Nettogrof
@steven, I didn't think it was you.
camickr