2

我有这个:

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

}

}

如何阻止黑色图像在框架上自动居中?

4

2 回答 2

5

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

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);
    }
}
于 2012-06-29T11:19:30.293 回答
2

JFrame 将BorderLayout 作为默认布局,当只有一个组件要添加到框架时,它默认进入框架的中心

您可以使用GroupLayout,并将组件放置到您想要的位置。GroupLayout 是由 NetBean 开发团队于 2005 年开发的,它可以在Window Builder Pro 中使用,它也是一个 GUI 构建,现在可以从 Google 免费获得。

于 2012-06-29T11:24:32.643 回答