Skip to content
Advertisement

How can I remove border on JLabel?

So I am trying to start a graphics program, where I have a JFrame that holds multiple JPanels. The JPanels need to combine to create 1 image, however when I run my program I see borders around the images. I cannot quite distinguish if the border is caused by the JLabel that holds the image or if it is because of the JPanel or because of the Layout Manager.

How can I remove the border? Would i need to change the layout manager? If so how?

import java.util.*;
import java.awt.*;
import javax.swing.*;

public class StarryNight {
    JFrame backGround;
    JPanel rootPanel;
    JLabel rootImage;

    public StarryNight(){
        backGround = new JFrame("Starry Starry Night");
        backGround.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        backGround.setResizable(false);
        backGround.setSize(1000,667);
        backGround.getContentPane().setBackground(Color.BLACK);
        backGround.setLayout(new BoxLayout(backGround.getContentPane(),BoxLayout.Y_AXIS));

        rootPanel = new JPanel();
        rootPanel.setSize(1000, 667);
        rootPanel.setBackground(Color.BLUE);;
        rootImage = new JLabel();
        rootImage.setIcon(new ImageIcon(getClass().getResource("Starry Night.jpg")));
        rootPanel.add(rootImage);


        JPanel jap = new JPanel();
        jap.setSize(1000,100);
        jap.setBackground(Color.GREEN);

        backGround.add(rootPanel);
        backGround.add(jap);
        backGround.pack();
        backGround.setVisible(true);


    }

    private static void runGUI()    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        StarryNight ssn= new StarryNight();
    }

    public static void main(String args[]){
        javax.swing.SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                runGUI();
            }
        });
    }
}

enter image description here

Advertisement

Answer

rootPanel = new JPanel();

By default a JPanel uses a FlowLayout which defaults to allows 5 pixels before/after components. So when you add our image to the panel you will see 5 pixels of space on all sides.

If you don’t want that space then look at the FlowLayout API and create a FlowLayout without spaces between the components and then add that layout to the rootPanel. Something like:

rootPanel = new JPanel( new FlowLayout(...) );

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement