0

Why cant I change the x and y coordinates of the icon? All I really need is to add the image to the screen. Do I even need to use a JLabel?

package bit;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class BIT extends JFrame
{
    JLabel CL;

    public BIT()
    {
        CL = new JLabel(new ImageIcon(this.getClass().getResource("final-image.jpg")));
        CL.setBounds(0,0,100,100);

        this.getContentPane().add(CL);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(5,5,1000,500);
        this.setResizable(false);
        this.setVisible(true);
    }
    public static void main(String[] args) 
    {
        new BIT();
    }
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276

2 Answers2

0

Unset the layout of the JFrame before adding controls with setBounds

this.setLayout(null);
Karan Punamiya
  • 8,603
  • 1
  • 26
  • 26
0

You cannot set the x & y coordinates of the JLabel as the JFrame is using its default BorderLayout layout manager which arranges its components according to layout implementation.

setBounds only works when using absolute positioning (or null layout) and this option should be avoided(!).

It appears you are trying to position the JLabel in the top left-hand corner of the frame (0, 0). To do this you could:

  • Left-align the label
  • Add the label in the PAGE_START position

This would be:

CL = new JLabel(new ImageIcon(...), JLabel.LEFT);
this.getContentPane().add(CL, BorderLayout.PAGE_START);
Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276