如何将JLabel与JPanel的底部对齐

tim*_*tim 1 java swing layout-manager

我希望JLabelitem3位于底部JPanel,因为有时它出现在我在窗口中的2d数组的顶部.我试着用 item3.setVerticalAlignment(JLabel.BOTTOM).方法,但它没有奏效.有什么建议?

public class Sokoban extends JPanel {

private Contents[][] field;
private Rectangle2D.Double r1;
private static final Color[] colours = {
        Color.BLACK, Color.RED, Color.GREEN, Color.CYAN, Color.MAGENTA, Color.BLUE, Color.YELLOW
    };

private LevelReader lr = new LevelReader();
private int currentLevel;
private Contents [][] levelData;
private int countMoves = 1;
JLabel item3 = new JLabel("ccc");


long time1;


public Sokoban(){
    lr.readLevels("m1.txt");

    this.setPreferredSize(new Dimension(900,500));
    this.setFocusable(true);
    this.requestFocus();
    this.addKeyListener(new MyKeyListener());
    initLevel(0);
    this.add(item3);
    item3.setVerticalAlignment(JLabel.BOTTOM);





}

public static void main (String[] args) {
    JFrame f = new JFrame("Sokoban");
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.setLayout(new FlowLayout());

    f.add(new Sokoban());


    f.pack();
    f.setVisible(true);  


}
Run Code Online (Sandbox Code Playgroud)

Rei*_*eus 8

您可以使用BorderLayout标签并将其添加到PAGE_END容器的位置

setLayout(new BorderLayout());
add(itemLabel, BorderLayout.PAGE_END);
Run Code Online (Sandbox Code Playgroud)

当然,您需要设置水平对齐以实现最初由标签JPanel FlowLayout容器生成的沿X轴的对齐

JLabel itemLabel = new JLabel("ccc", JLabel.CENTER);
Run Code Online (Sandbox Code Playgroud)