0

I'm new to java swing and I've been spending two days already on how to make a dynamically resizing background for jframe using a jlabel. I've searched a lot of videos on youtube and tried different suggestions here in stackoverflow but I did not succeed.

So here's the situation. I made a GUI using the "Design View" in Netbeans. The first component that I have (below jframe) is a jSplitPane (I made this transparent). Inside this split pane is many many other components. I succeeded in making a background image using the jlabel but it won't dynamically resize with the jframe (when i resize the window).

Here's a sample code of how I did this:

    // This is the constructor. 
    public MyGUI() {
        initComponents(); //auto-generated code where the many many other components are made
        /*
         * other methods called here (background is not affected by these)
         */

        setBackgroundImage();
    }

    private void setBackgroundImage(){
        JLabel background = new JLabel();
        setContentPane(background);
        background.add(mySplitPane); // this is the jSplitPane I mentioned in my explanation

        BufferedImage image = null;
        try {
            image =ImageIO.read(new File("C:\\Users\\Documents\\vinylRecord.png"));

        } 
        catch (IOException e) {
            e.printStackTrace();
        }

        background.setIcon(new ImageIcon(image));
    }

Note: I can't post every part of my code but the setBackgroundImage() is exactly what it is. Please tell me if you need to see other parts of it. Thanks!

Hello
  • 1
  • 2
  • How about using a LayoutManager? – Alexander Heim Sep 21 '17 at 09:43
  • I've tried that too but still the background image won't resize. – Hello Sep 21 '17 at 09:46
  • First of all you should use an appropriate [LayoutManager](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). For example `BorderLayout` or `GridBagLayout`. Also you should use `JPanel` instead of `JLabel`. [Here](https://stackoverflow.com/questions/11959758/java-maintaining-aspect-ratio-of-jpanel-background-image) is a very good example. – Sergiy Medvynskyy Sep 21 '17 at 09:48
  • Resizing a background image isn´t a really good idea. There is a reason why most programms don´t have a structured one in the first place but rather just a plain color or color pattern. Even if a programm uses a image in the background the application would probably not be resizeable. Not saying it´s impossible but just not worth the amount of work – Alexander Heim Sep 21 '17 at 09:57
  • @SergiyMedvynskyy Thanks! That solved my problem. I used JLabel before because many of the tutorials in youtube and other sites suggested to use it but JPanel should definitely be used. – Hello Sep 21 '17 at 10:46
  • @AlexanderHeim Yeah it doesn't seem to look good but I'll use it anyway as I don't have a choice right now. – Hello Sep 21 '17 at 10:49

0 Answers0