-3

So I already made a panel that contains multiple labels, text fields, and buttons. And within the panel I placed another JLabel and went to properties -> icon and uploaded an image, however the image(which I'm trying to use as the background) does not scale to the panel.

What can I do to make the image fit to scale the panel dimension? For example, this is a New Project JFrame named Sample and I have added a JPanel with variable name pnMain and a JLabel with variable name lblBackground. With the label I went to Properties -> Icon then uploaded an image.

package tempo;

public class Sample extends javax.swing.JFrame {

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

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        pnMain = new javax.swing.JPanel();
        lblBackground = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        pnMain.setLayout(null);

        lblBackground.setIcon(new javax.swing.ImageIcon("C:\\Users\\Anderson\\Desktop\\Monkee-Boy Blurred Backgrounds\\bkg-3.jpg")); // NOI18N
        pnMain.add(lblBackground);
        lblBackground.setBounds(0, 0, 400, 280);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnMain, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnMain, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }                  

    public static void main(String args[]) {
        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(Sample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Sample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Sample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Sample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Sample().setVisible(true);
            }
        });
    }

    // Variables declaration                     
    private javax.swing.JLabel lblBackground;
    private javax.swing.JPanel pnMain;
    // End of variables declaration                   
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 3
    Welcome to Stack Overflow, please take the [tour], go through the [help] and learn [ask], then come back and post a valid [mcve] that demonstrates your issue including an image of expected and actual output – Frakcool Mar 04 '17 at 21:49
  • 2
    A `JLabel` would have to be extended and custom painted in order to scale an image. It's easier though, to extend and custom paint a `JPanel` - given it will correctly account for the size of the components it contains. **Oops!** I wrote that thinking you were using the image as a BG, and the label to contain the other components. :P – Andrew Thompson Mar 04 '17 at 21:51
  • If you want the image to fit the `JPanel`'s size, you might want to try with custom painting it... – Frakcool Mar 04 '17 at 21:51
  • 1
    In addition to the comment about the MCVE suggested by @Frakcool.. One way to get image(s) for an example (e.g the image that needs scaling) is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Mar 04 '17 at 21:55
  • [Scaling an image](http://stackoverflow.com/questions/11959758/java-maintaining-aspect-ratio-of-jpanel-background-image/11959928#11959928) – MadProgrammer Mar 04 '17 at 22:05
  • @MadProgrammer thanks for the link, I saw that link before. I am confused where I implement the code: Image.getScaledInstance – Anderson Fruithandler Mar 04 '17 at 22:28
  • @Frakcool I edited the post with the example code, do you mind looking over it again and see if you can assist me please? – Anderson Fruithandler Mar 04 '17 at 22:29
  • @AndersonFruithandler First, I wouldn't use `getScaledInstance`, as mentioned in the link, it's not the best available choice. You would use between loading the original image and drawing the scaled version, but you will need to know how large you want the image to be first – MadProgrammer Mar 04 '17 at 22:31
  • `ImageIcon("C:\\Users\\Anderson\\Desktop\\Monkee-Boy Blurred Backgrounds\\bkg-3.jpg"));` Strange as it may seem, that file does not exist here. That's why I suggested **hot linking** to one that will work for **anyone that runs the code!** – Andrew Thompson Mar 04 '17 at 22:56
  • Oh, and before I forget.. Please use code formatting for code and code snippets, structured documents like HTML/XML or input/output. To do that, select the text and click the `{}` button at the top of the message posting/editing form. – Andrew Thompson Mar 04 '17 at 22:57
  • `pnMain.setLayout(null);` FFS! As if this is not discussed at least twice a day around here. Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Mar 04 '17 at 23:01
  • @AndrewThompson yes I was also going to ask how to redirect the file path so that instead of linking it from my desktop, I can save it into the Project folder in the Netbeans and bring it up from there. But at the moment I am first trying to focus on resizing the background to fit to scale the panel. – Anderson Fruithandler Mar 04 '17 at 23:07
  • *"But at the moment I am first trying to focus on resizing the background to fit to scale the panel."* Wait.. so **you** don't care if **we** focus on the problem **you** are asking about? Because part of the point of posting an MCVE that **we** can run is to make it easy for us to help. If you don't want to put the effort in to make it easy, no problem. There's lots of other people need help, and we have our own lives. Good luck with it. – Andrew Thompson Mar 04 '17 at 23:43
  • Provide ASCII art or a simple drawing of the *intended* layout of the components in the GUI at minimum size, and if resizable, with more width and height. – Andrew Thompson Mar 05 '17 at 16:47

1 Answers1

0

You can use the Stretch Icon and add the Icon to a JLabel and the label to a panel. So the layout manager of the panel will need to resize any component added to it. An easy way to do this is to set the layout manager of the panel to a BorderLayout.

The Icon will resize to fill the space available to the label. So if the label resizes, the Icon will resize.

You can also control if the scaling is proportional or not.

camickr
  • 321,443
  • 19
  • 166
  • 288