我希望 JLabel
item3 位于 JPanel
的底部,因为有时它会出现在我在窗口中的二维数组的顶部。我尝试使用 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);
}
最佳答案
您可以使用 BorderLayout
并将标签添加到容器的 PAGE_END
位置
setLayout(new BorderLayout());
add(itemLabel, BorderLayout.PAGE_END);
当然,您需要设置水平对齐方式以实现沿 X 轴的对齐方式,就像最初由标签的 JPanel
FlowLayout
容器生成的那样
JLabel itemLabel = new JLabel("ccc", JLabel.CENTER);
关于java - 如何将 JLabel 对齐到 JPanel 的底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23068197/