JSwing Background Download Image Strange

enter image description here enter image description here

enter image description here

enter image description here

I cannot understand how I would add in the background, with all my panels.

I tried to set the content frame of the JFrame as a label with the image, and the frame really shows, it just does not show the image, as shown above.

This is the code I used.

frame.setContentPane(new JLabel(new ImageIcon("res/Wallpaper.png")));

The second attempt I used was to add (not install) the image to the frame content area. This does not work, as shown in the second figure above, and it only displays panels, but no background. The code is at the bottom.

frame.getContentPane().add(new JLabel(new ImageIcon("res/Wallpaper.png")));

The third attempt I tried was to subclass the JComponent and override the paintComponents method and then set it as a contentpane object. This does not work, and instead my screen is blank.

, , 1- JFrame. 3- .

        File img = new File("res/Wallpaper.png");

    BufferedImage myImage;
    try {
        myImage = ImageIO.read(img);
        frame.setContentPane(new ImagePanel(myImage));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

4- , , , . , , , .

, 4- . 4- .

        BufferedImage myPicture;
    try {
        myPicture = ImageIO.read(new File("res/Wallpaper.png"));
        JLabel picLabel = new JLabel(new ImageIcon(myPicture));
        pMain.add(picLabel);
    } catch (IOException e) {
        e.printStackTrace();
    }

, JPanels .

, , JLabel, , , .

- , , .

- , , . , , , . Ex. Windows, , .

. , , - .

EDIT: , , JFrame, .

, , , , -, , . , : 4 JPanels , , , 1- . .

, , , , .

, , .

, , paintComponent , setcontentPane() . , , , .

, :

public class LoginScreen {

JCheckBox remember_User;
JButton login, create_Account, forums, faqs;
Border whiteLine;
JTextField userField;
JFormattedTextField passField;

private void createView() {
    // Created essential details for the frame
    JFrame frame = new JFrame();
    frame.setTitle("Name of the game");
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Defining panels and a constraint on the bottomPanel.
    // More info - Total amt of panels: 5
    // pLogin and pInfo are in the bottomCompPanel and bottomCompPanel is in
    // bottomPanel
    // bottom panel is in pMain
    // Giving panels some attributes like backgrounds and borders
    JPanel pMain = new JPanel(new BorderLayout());
    pMain.setBorder(BorderFactory.createMatteBorder(3, 3, 6, 3,
            Color.DARK_GRAY));
    frame.getContentPane().add(pMain);

    whiteLine = BorderFactory.createLineBorder(Color.LIGHT_GRAY);

    JPanel pLogin = new JPanel(new GridBagLayout());
    pLogin.setBackground(Color.cyan);
    pLogin.setPreferredSize(new Dimension(400, 250));
    pLogin.setBorder(whiteLine);

    JPanel pInfo = new JPanel(new GridBagLayout());
    pInfo.setBackground(Color.green);
    pInfo.setPreferredSize(new Dimension(200, 100));
    pInfo.setBorder(whiteLine);

    JPanel bottomCompPanel = new JPanel(new GridBagLayout());
    GridBagConstraints bGBC = new GridBagConstraints();
    bGBC.gridx = 0;
    bGBC.gridy = 0;
    bGBC.insets = new Insets(0, 20, 0, 0);
    bGBC.anchor = GridBagConstraints.PAGE_END;

    bottomCompPanel.add(pLogin, bGBC);
    bGBC.gridx++;
    bottomCompPanel.add(pInfo, bGBC);

    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));

    bottomPanel.add(bottomCompPanel);
    pMain.add(bottomPanel, BorderLayout.SOUTH);
    frame.setVisible(true);
}

public static void main(String[] args) {
    LoginScreen login = new LoginScreen();
    login.createView();
}

}

2: , @peeskillet 1st. , , , . P.S JLabel .

private void createView() {

    //Created essential details for the frame
    JFrame frame = new JFrame();
    frame.setTitle("Name of the game");
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);

    JLabel background = new JLabel(new ImageIcon("res/Wallpaper.png"));
    background.setLayout(new BorderLayout());
    frame.setContentPane(background);


    //Defining panels and a constraint on the bottomPanel. 
    //More info - Total amt of panels: 5
    //pLogin and pInfo are in the bottomCompPanel and bottomCompPanel is in bottomPanel
    //bottom panel is in pMain
    //Giving panels some attributes like backgrounds and borders

    whiteLine = BorderFactory.createLineBorder(Color.LIGHT_GRAY);

    JPanel pLogin = new JPanel(new GridBagLayout());
    pLogin.setBackground(Color.cyan);
    pLogin.setPreferredSize(new Dimension(400,250));
    pLogin.setBorder(whiteLine);

    JPanel pInfo = new JPanel(new GridBagLayout());
    pInfo.setBackground(Color.green);
    pInfo.setPreferredSize(new Dimension(200,100));
    pInfo.setBorder(whiteLine);

    JPanel bottomCompPanel = new JPanel(new GridBagLayout());

    GridBagConstraints bGBC = new GridBagConstraints();
    bGBC.gridx = 0;
    bGBC.gridy = 0;
    bGBC.insets = new Insets(0,20,0,0);
    bGBC.anchor = GridBagConstraints.PAGE_END;

    bottomCompPanel.add(pLogin, bGBC);
    bGBC.gridx++;
    bottomCompPanel.add(pInfo, bGBC);

    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));

    bottomPanel.add(bottomCompPanel);
    background.add(bottomPanel, BorderLayout.SOUTH);
+4
2

" JFrame "

JLabel. .

import java.awt.*;
import java.net.URL;
import javax.swing.*;
import javax.swing.border.Border;

public class BackgroundImage {

    private static final String IMG = "http://i.stack.imgur.com/JEoYs.jpg";

    private void init() throws Exception {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel background = new JLabel(new ImageIcon(new URL(IMG)));
        background.setLayout(new GridBagLayout());
        background.add(loginPanel());
        f.setContentPane(background);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private JPanel loginPanel() {
        Border whiteLine = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
        JPanel pLogin = new JPanel(new GridBagLayout());
        pLogin.setBackground(Color.cyan);
        pLogin.setPreferredSize(new Dimension(400, 250));
        pLogin.setBorder(whiteLine);
        return pLogin;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                new BackgroundImage().init();
            } catch (Exception ex) {}
        });
    }
}

enter image description here

" JComponent paintComponents, contentpane"

paintComponent ( "s" ), , JLabel, . JComponent layout null . .

import java.awt.*;
import java.net.URL;
import javax.swing.*;
import javax.swing.border.Border;

public class BackgroundImage {

    private static final String IMG = "http://i.stack.imgur.com/JEoYs.jpg";

    private void init() throws Exception {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent background = new BackgroundComponent(new ImageIcon(new URL(IMG)));
        background.setLayout(new GridBagLayout());
        background.add(loginPanel());
        f.setContentPane(background);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private JPanel loginPanel() {
        Border whiteLine = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
        JPanel pLogin = new JPanel(new GridBagLayout());
        pLogin.setBackground(Color.cyan);
        pLogin.setPreferredSize(new Dimension(400, 250));
        pLogin.setBorder(whiteLine);
        return pLogin;
    }

    class BackgroundComponent extends JComponent {
        public ImageIcon background;
        public BackgroundComponent(ImageIcon background) {
            this.background = background;
        }
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(background.getIconWidth(), background.getIconHeight());
        }
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(background.getImage(),
                        0, 0,
                        background.getIconWidth(), 
                        background.getIconHeight(), this);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                new BackgroundImage().init();
            } catch (Exception ex) {}
        });
    }
}

enter image description here

() JPanel JComponent , , JPanel , FlowLayout.


UPDATE

, .

Outer (main panel)     -- BorderLayout
Bottom (bottom panel)  -- BoxLayout inside (south) of outer layout

BorderLayout , opaque false, BorderLayout .

BoxLayout

import java.awt.*;
import java.net.URL;
import javax.swing.*;
import javax.swing.border.Border;

public class BackgroundImage {

    private static final String IMG = "http://i.stack.imgur.com/JEoYs.jpg";
    private final Border whiteLine = BorderFactory.createLineBorder(Color.LIGHT_GRAY);


    private void init() throws Exception {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent background = new BackgroundComponent(new ImageIcon(new URL(IMG)));
        background.setLayout(new BorderLayout());
        background.add(bottomPanel(), BorderLayout.SOUTH);
        f.setContentPane(background);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private JPanel bottomPanel() {
        JPanel bottomPanel = new JPanel();
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        BoxLayout layout = new BoxLayout(bottomPanel, BoxLayout.X_AXIS);
        bottomPanel.setLayout(layout);
        bottomPanel.setOpaque(false);
        bottomPanel.add(Box.createHorizontalGlue());
        bottomPanel.add(loginPanel());
        bottomPanel.add(Box.createRigidArea(new Dimension(10, 0)));
        bottomPanel.add(infoPanel());
        return bottomPanel;
    }

    private JPanel infoPanel() {
        JPanel pInfo = new JPanel(new GridBagLayout());
        pInfo.setAlignmentY(Component.BOTTOM_ALIGNMENT);
        pInfo.setBackground(Color.green);
        pInfo.setMaximumSize(new Dimension(200, 100));
        pInfo.setPreferredSize(new Dimension(200, 100));
        pInfo.setBorder(whiteLine);
        return pInfo;
    }

    private JPanel loginPanel() {
        JPanel pLogin = new JPanel(new GridBagLayout());
        pLogin.setAlignmentY(Component.BOTTOM_ALIGNMENT);
        pLogin.setBackground(Color.cyan);
        pLogin.setPreferredSize(new Dimension(400, 250));
        pLogin.setMaximumSize(new Dimension(400, 250));
        pLogin.setBorder(whiteLine);
        return pLogin;
    }

    class BackgroundComponent extends JComponent {

        public ImageIcon background;

        public BackgroundComponent(ImageIcon background) {
            this.background = background;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(background.getIconWidth(), background.getIconHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(background.getImage(),
                    0, 0,
                    background.getIconWidth(),
                    background.getIconHeight(), this);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                new BackgroundImage().init();
            } catch (Exception ex) {
            }
        });
    }
}

enter image description here

.

+2

JLayeredPane setOpaque (boolean).

:

public class BackgroundImageTest{
    private JFrame frame;

    public BackgroundImageTest() {
        frame = new JFrame("Background Image Frame");

        // set frame properties

        JPanel panel = new JPanel(new FlowLayout());
        panel.setOpaque(false);
        JButton btn = new JButton("Change Background");
        panel.add(btn);

        btn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
                setBackgroundImage(getImage(new File("Wallpaper2.png")));
            }
        });

        JPanel main = (JPanel) frame.getContentPane();
        main.setLayout(new FlowLayout());
        main.add(panel);
        main.setOpaque(false);

        setBackgroundImage(getImage(new File("Wallpaper.png")));

        frame.setVisible(true);
    }

    private Image getImage(File imageFile) {
        BufferedImage image = null;

        try {
            image = ImageIO.read(imageFile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return image;
    }

    private void setBackgroundImage(Image img) {
        if(img == null) return;

        ImageIcon ii = new ImageIcon(img);
        JLabel lblBG = new JLabel(ii);
        lblBG.setName("BackgroundImageLabel");

        JLayeredPane layeredPane = frame.getLayeredPane();

        Component[] comps = layeredPane.getComponentsInLayer(new Integer(Integer.MIN_VALUE));
        for (int i = 0; i < comps.length; i++) {
            System.out.println(comps[i].getName());

            if (comps[i] instanceof JLabel && comps[i].getName().equals("BackgroundImageLabel")){
                layeredPane.remove(comps[i]);
                break;
            }
        }

        layeredPane.add(lblBG, new Integer(Integer.MIN_VALUE));
        lblBG.setBounds(0,0,ii.getIconWidth(), ii.getIconHeight());
    }
}
+1

Source: https://habr.com/ru/post/1611326/


All Articles