How to make the image scale its size automatically according to the parent JLabel's size, in Netbeans GUI Builder?

StackOverflow https://stackoverflow.com/questions/23322564

Pregunta

BACKGROUND:- I am required to make a Swing GUI using Netbeans GUI Builder. The first sub-task is to display an image in the entire background.

I have followed a tutorial to get that done. I have basically made a JFrame, set its layout to GridBagLayout and then added a transparent (by unchecking the opaque property) JPanel to it. (Question 1)

After that I added a JLabel to the JFrame, Removed its text and added an image to it. (Question 2)

QUESTIONS:-

  1. First, when I add the JPanel, it does not show its resize handles. I Googled a bit and found this tutorial, in which it can be seen that when they create a JPanel, it automatically shows its resize handles, which can be dragged to resize it.

    But mine doesn't (screenshot below) So is there some property or something which can be adjusted so that I can resize it? Because my intention is to use this transparent panels to contain components (buttons etc.) on the background, so it should elapse the entire screen/window/JFrame parent. enter image description here

  2. Second, since the image I am using has some 1024x768 dimensions, so it appears to be way bigger than its parent components. enter image description here

    Since I am a noob and I am not sure if the size of the background image needs to be adjusted by somehow measuring the pixel width and pixel height of the parent and then converting the actual image's size to that size in some program like Adobe Photoshop. But I am sure there must a more practical way to do that.

    I want the image to automatically resize itself according to the size of the parent when it is initially placed on on its parent JLabel. How can I do that? Please tell me the easiest way, preferably in the GUI Builder.

I also want to ensure that the image size, its parent JLabel's size, JPanel's size will all adjust to the frame when the I change the size of the window later when using this application, or if there is a way to disable the sizing of the window completely.


EDIT1 @Braj

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.dev_nna.dbp;


public class JFrameParent extends javax.swing.JFrame {

    /**
     * Creates new form JFrameParent
     */
    public JFrameParent() {
        initComponents();
    }

    /**
     * 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();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

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

        getContentPane().add(jPanel1, new java.awt.GridBagConstraints());

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dev_nna/dbp/scheduler/resources/Abstract-white-and-blue-backgrounds.jpg"))); // NOI18N
        jLabel1.setText("jLabel1");
        getContentPane().add(jLabel1, new java.awt.GridBagConstraints());

        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(JFrameParent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameParent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameParent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameParent.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() {
                new JFrameParent().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}
¿Fue útil?

Solución

" or if there is a way to disable the sizing of the window completely."

You can set the resizable property of the frame to false. From NetBeans GUI Builder

  1. Highlight/select the frame component from the design view, or from the navigator window.
  2. Go to the properties window on the right and look for the property resizable and make sure it's unchecked

"I also want to ensure that the image size, its parent JLabel's size, JPanel's size will all adjust to the frame when the I change the size of the window"

One way is to paint the background onto the background panel, instead of using a label with an icon. You can see an example of that here. For the GUI Builder, the easiest way (without having to edit the auto-generated code, which I don't recommend, if you don't know what you are doing) is to use a JPanel form instead of a JFrame form. Paint on the JPanel form, then you can add that JPanel form to the JFrame form. You can see here for an easy way to add the JPanel form to the JFrame form.


UPDATE

So your JPanel form class will ultimately look something like this

public class PanelForm extends javax.swing.JPanel {
    private BufferedImage image;

    public PanelForm() {
        try {
            image = ImageIO.read(getClass().getResource("/path/to/image/png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }  
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(500, 500);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new PanelForm());     //  <--- add it here
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top