我是 Java GUI 编程新手,我对 BoxLayout
有一个奇怪的问题:
我有一个带有 Icon
的 JLabel
。添加到标签中的是两个 JButton
。 Jlabel
放置在 JFrame
的 BorderLayout
的 CENTER
位置。现在,即使我调整 JFrame
的大小,我也希望这两个 JButton
始终位于 JLabel
的中心。使用setAlignmentX()
,Jbuttons 水平居中,但使用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);
}
}
请帮忙! :-((((
最佳答案
but there is no solution with setAlignmentY() for the vertical direction.
在两个组件之前和之后使用“胶水”。请参阅 Swing 教程中关于 How to Use Box Layout 的部分了解更多信息和示例。
虽然 MadProgrammers 评论使用 GridBagLayout
是一个更简单的解决方案,但了解“glue”和“struts”对于自定义 BoxLayout
的布局很有帮助。
关于java - 如何将 JButtons 置于 BoxLayout 中居中 JLabel 的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23049814/