[英]How to Center JButtons in a centered JLabel in a BoxLayout?
我是Java GUI編程的新手,但BoxLayout
有一個奇怪的問題:我有一個帶Icon
的JLabel
。 添加到標簽的是兩個JButtons
。 Jlabel
從JFrame
放置在BorderLayout
的CENTER
位置。 現在,我希望這兩個JButtons
始終位於JLabel
的中心,即使我調整JFrame
大小也是如此。 使用setAlignmentX()
,Jbutton處於水平居中位置,但是對於setAlignmentY()
,垂直方向沒有解決方案。
這是代碼:
package footballQuestioner;
import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Houdini {
public static void main(String[] args) {
JFrame frame = new House();
}
}
class House extends JFrame {
private JLabel label = new JLabel(
new ImageIcon(
"C:\\Users\\laudatio\\Documents\\Java\\MyProject\\src\\footballQuestioner\\footballfield.jpg")
);
private JButton one=new JButton("one");
private JButton two=new JButton("two");
public House() {
label.setLayout(new BoxLayout(label, BoxLayout.Y_AXIS));
label.add(one);
label.add(two);
one.setAlignmentX(CENTER_ALIGNMENT);
one.setAlignmentY(CENTER_ALIGNMENT);
two.setAlignmentX(CENTER_ALIGNMENT);
two.setAlignmentY(CENTER_ALIGNMENT);
setLayout(new BorderLayout());
setLocation(300, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
add(label,BorderLayout.CENTER);
pack();
setVisible(true);
}
}
請幫忙! : - ((((
但是使用setAlignmentY()在垂直方向上沒有解決方案。
在兩個組件之前和之后使用“膠水”。 有關更多信息和示例,請參見Swing教程中有關如何使用框布局的部分。
盡管MadProgrammers評論說使用GridBagLayout
是一個更簡單的解決方案,但是了解“ glue”和“ struts”有助於自定義BoxLayout
的布局。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.