1

i am using netbeans to built a image viewer using swings.. using the netbeans swing builder GUI i got the following code, i have put a jpanel in a parent jframe. all that i want to do as of for now is open an image in the jpanel and add it to jframe

here is the code:

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

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

/**
 *
 * @author Tempo
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() throws IOException {
        initComponents();
        final BufferedImage gray_img=ImageIO.read(new File("C:/Users/Tempo/Pictures/sucess.png"));
                    this.setBounds(0, 0, gray_img.getWidth(), gray_img.getHeight());
                    this.jPanel1 =new JPanel(){
                    @Override
                    public void paint(Graphics g) {
                            // TODO Auto-generated method stub
                            super.paint(g);
                            g.drawImage(gray_img, 0, 0, null);
                    }

                                    };
                    this.add(jPanel1);

    }

    /**
     * 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() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 440, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 276, Short.MAX_VALUE)
        );

        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()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(153, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

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

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    NewJFrame frame=new NewJFrame();
//                    frame.setPreferredSize(new Dimension(800,600));
//                    frame.setMinimumSize(new Dimension(200,400));


                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

when the file is run, it only displays a blank jframe with no image/(Jpanel) in it!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
shridatt
  • 896
  • 4
  • 15
  • 39
  • Instead of using Absolute Paths for images, better provide Relative Paths, so that they can run on any machine without Modification of any sorts regarding the paths to images. Have a look at [this answer](http://stackoverflow.com/a/9866659/1057230) of mine for more insight. Though if you doing it manually, there is one more [answer](http://stackoverflow.com/a/11372350/1057230) for more help here :-) – nIcE cOw Aug 14 '12 at 09:34

1 Answers1

4

You've not providing any constraints to the LayoutManager and it appears to be ignoring your panel.

The other solution is, create a custom panel with the paint routine you need in a separate class file, compile the project, drag and drop the custom pane into the NewJFrame form

Alternatively, until you get a grip for it, code the layout by hand. It will give you a greater appreciation for what's going on and make fixing these issues easier in the future.

Also, don't override 'paint' unless you have a REALLY good reason for doing so, it's much better to use paintComponent instead.

Oh, this this.setBounds(0, 0, gray_img.getWidth(), gray_img.getHeight()) is a really bad idea. You'll probably find that the layout manager has overridden these values.

Better to use a JScrollPane for variable width/height components. And you're probably going to need to supply preferred size details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • writing a custom panel helped :)... but only portion of image is getting displayed in the panel, want to make the image change its resolution as per the panel size.. – shridatt Aug 14 '12 at 06:23
  • 1
    So, you want to scale it down? The easiest is to use `Image.getScaledInstance` which is a member of `BufferedImage`. Just remember, you're responsible for the aspect ratio. `getScaledInstance` is not the fastest, not the best scaling algorithm, but it is the easiest. If you want more of an insight, have a read through http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html – MadProgrammer Aug 14 '12 at 06:39
  • 1
    and to use paintComponent() instead of paint() – mKorbel Aug 14 '12 at 06:44
  • i used paint @mKorbel at this point to just get hang of it.... will try out paintcomponent – shridatt Aug 14 '12 at 07:54