本文為大家解析java Swing布局管理中的BoxLayout布局,供大家參考,具體內容如下
BoxLayout:可以指定在容器中是否對控件進行水平或者垂直放置,比 FlowLayout 要更為靈活
BoxLayout與其他布局管理器稍有不同,必須向其構造函數中傳遞容器實例的引用,由該容器使用BoxLayout。另外必須指定BoxLayout中組件的布局方式:垂直排列(按列)或水平排列(按行)。用水平組件和垂直組件的不同組合嵌套多面板的作用類似于 GridBagLayout,但沒那么復雜。
1.構造函數
BoxLayout(Container target, int axis) :創建一個將沿給定軸放置組件的布局管理器。
LINE_AXIS :指定應該根據目標容器的 ComponentOrientation 屬性確定的文本行方向放置組件。
PAGE_AXIS :指定應該根據目標容器的 ComponentOrientation 屬性確定的文本行在頁面中的流向來放置組件。
X_AXIS :指定組件應該從左到右放置。
Y_AXIS :指定組件應該從上到下放置。
2.常用方法
getAxis() :返回用于布局組件的軸。
getLayoutAlignmentX(Container target) :返回容器沿 X 軸的對齊方式。
getLayoutAlignmentY(Container target) : 返回容器沿 Y 軸的對齊方式
getTarget() :返回使用此布局管理器的容器。
3.實例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<span style= "font-family:KaiTi_GB2312;font-size:18px;" > import java.awt.Container; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.UIManager; public class BoxLayoutDemo { public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } JFrame frame = new JFrame( "BoxLayout Test" ); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container panel = frame.getContentPane(); panel.setLayout( new BoxLayout(panel, BoxLayout.Y_AXIS)); for ( float align = 0 .0f; align <= 1 .0f; align += 0 .25f) { JButton button = new JButton( "X align = " + align); button.setAlignmentX(align); panel.add(button); } frame.setSize( 400 , 300 ); frame.setVisible( true ); } } </span> |
4.結果

以上就是本文的全部內容,希望對大家學習java Swing布局管理有所幫助和啟發,謝謝大家的閱讀。