[英]How can I align all my swing components to the top left of JPanel/JFrame
[英]How can I align all elements to the left in JPanel?
我想讓我的JPanel中的所有元素都對齊到左邊。 我試着用以下方式做到這一點:
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
因此,Java使用所有元素的左側作為元素的位置,然后將所有元素放在JPanel的中心(而不是左側部分)。
我發現在左邊放置對象的最簡單方法是使用FlowLayout。
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
通常在此面板中添加組件會將其放在左側
您應該在要對齊的組件上使用setAlignmentX(..)
,而不是在包含它們的容器上。
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(c1);
panel.add(c2);
c1.setAlignmentX(Component.LEFT_ALIGNMENT);
c2.setAlignmentX(Component.LEFT_ALIGNMENT);
我最喜歡使用的方法是BorderLayout方法。 以下是組件可以進入的每個位置的五個示例。示例是組件是否為按鈕。 我們將它添加到JPanel,p。 該按鈕將被稱為b。
//To align it to the left
p.add(b, BorderLayout.WEST);
//To align it to the right
p.add(b, BorderLayout.EAST);
//To align it at the top
p.add(b, BorderLayout.NORTH);
//To align it to the bottom
p.add(b, BorderLayout.SOUTH);
//To align it to the center
p.add(b, BorderLayout.CENTER);
輸入以下內容時不要忘記導入它:
import java.awt.BorderLayout;
BorderLayout類中還有其他方法涉及方向,但如果您對此感到好奇,可以自行研究。 我希望這有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.