改变JLabel的位置

时间:2015-03-13 19:07:07

标签: java swing jlabel null-layout-manager

经过大量的研究,我只能使用标签获得该板图像。现在我无法改变它的立场。我尝试了很多功能。我需要什么功能

public class Board extends JFrame {
    private ImageIcon image;
    private JLabel label;

    public Board() {
        image = new ImageIcon(getClass().getResource("board.png"));
        label = new JLabel(image);
        label.setLocation(200, 0);  //This is the one that I expected to do the thing
        add(label);
    }

    public static void main(String [] args) {
        Board b = new Board();
        b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        b.setVisible(true);
        b.setSize(1280, 1000);
    }
}

2 个答案:

答案 0 :(得分:2)

请勿尝试手动设置组件的位置。 Swing旨在与布局管理器一起使用。有关详细信息,请阅读Using Layout Managers上的Swing教程中的部分。

定位组件的一种方法是为组件提供Border。所以你可以这样做:

label.setBorder( new EmptyBorder(200, 0, 0, 0) );

本教程还有一个关于How to Use Borders的部分。

答案 1 :(得分:0)

首先:您不应手动移动组件。这应留给布局管理员。但是你可以。您面临的基本问题是 - 或至少我认为 - :您的主板仍然有布局管理器设置,这将继续布局板,并且由于这个以及移动(并处理大小)您是组件。只需在定位标签之前调用setLayout(null);并指定大小,它就应该有效。