JLabel ImageIcon:停止帧中的自动居中

时间:2012-06-29 11:16:53

标签: java swing jframe jlabel layout-manager

我有这个:

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);

}

}

如何阻止黑色图像自动居中于画面?

2 个答案:

答案 0 :(得分:5)

它似乎是唯一的组件,它填充了框架。如果它是唯一的组件,请使用文本对齐或FlowLayout

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);
    }
}

答案 1 :(得分:2)

JFrame将 BorderLayout作为默认布局,当只有一个组件添加到框架中时,默认情况下会转到中心框架

您可以使用 GroupLayout ,并将该组件放置到所需的位置。 GroupLayout是由NetBean开发团队于2005年开发的,它可以在 Window Builder Pro中使用,也可以从GUI免费获得。