Search code examples
javaswingjframejlabellayout-manager

JLabel ImageIcon: stop auto centering in the frame


I have this:

import javax.swing.*;
import java.awt.Canvas;
import java.awt.image.BufferedImage;

public class test extends Canvas{

public static JFrame frame;
public static int WIDTH = 800;
public static int HEIGHT = 600;
public static BufferedImage img;
public static int[] pixels;
public static boolean running=true;

public static void main(String[] a){

        img = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
        frame = new JFrame("WINDOWw");
        frame.add(new JLabel(new ImageIcon(img)));
        frame.pack();
        frame.setVisible(true);
        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

How can I stop that black image from auto centering on the frame?


Solution

  • It seems to be the only component, it fills the frame. Use text alignment or a FlowLayout if it is the only component.

    TestLabelPlacement - FlowLayout

    import javax.swing.*;
    import java.awt.FlowLayout;
    import java.awt.image.BufferedImage;
    
    public class TestLabelPlacement {
    
        public static JFrame frame;
        public static int WIDTH = 200;
        public static int HEIGHT = 150;
        public static BufferedImage img;
    
        public static void main(String[] a){
    
            img = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
            frame = new JFrame("Window");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            frame.setLayout(new FlowLayout(FlowLayout.LEADING));
            frame.add(new JLabel(new ImageIcon(img)));
            frame.pack();
            frame.setVisible(true);
            // WRONG!  That is the size of the image, not the frame!
            //frame.setSize(WIDTH, HEIGHT);
        }
    }