Swing-setAlignmentX()用法-入門


先看下API:

public void setAlignmentX(float alignmentX)

設置垂直對齊方式。

參數: alignmentX - 新的垂直對齊方式

 

網上關於這個函數的詳細情況介紹的不多,JAVA布局管理器提到說, setAlignmentX(left,right)只有在布局是BoxLayout.Y_AXIS才效,而setAlignmentY(top,button)在布局為BoxLayout.X_AXIS才效果。我基本同意這個理解,也就是說,setAlignmentX()用於使用了BoxLayout.Y_AXIS時,將控件在X軸方向設置為左對齊、右對齊或居中對齊;setAlignmentY()用於使用了BoxLayout.X_AXIS時,將控件在Y軸方向設置為頂對齊、底對齊或居中對齊。以下是測試代碼:

 

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.TextArea;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
import javax.swing.border.EtchedBorder;

/*
 * 2015-06-13
 */
public class setAlignmentDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        //第一個panel,垂直排列
        JPanel  jpanelY = new JPanel();
        jpanelY.setLayout(new BoxLayout(jpanelY,BoxLayout.Y_AXIS));
        jpanelY.setBorder(BorderFactory.createTitledBorder("BoxLayout.Y_AXIS"));
        JButton   buttonY1 = new JButton("LEFT_ALIGNMENT");
        JButton   buttonY2 = new JButton("RIGHT_ALIGNMENT");
        JButton   buttonY3 = new JButton("CENTER_ALIGNMENT");
        
        buttonY1.setAlignmentX(Component.LEFT_ALIGNMENT);
        buttonY2.setAlignmentX(Component.RIGHT_ALIGNMENT);
        buttonY3.setAlignmentX(Component.CENTER_ALIGNMENT);
        
        jpanelY.add(buttonY1);
        jpanelY.add(buttonY2);
        jpanelY.add(buttonY3);
      //第二個panel,水平排列
        JPanel  jpanelX=new JPanel();
        jpanelX.setLayout(new BoxLayout(jpanelX,BoxLayout.X_AXIS));
        jpanelX.setBorder(BorderFactory.createTitledBorder("BoxLayout.X_AXIS"));
        
        JButton buttonX1 = new JButton("TOP_ALIGNMENT");
        JButton buttonX2 = new JButton("BOTTOM_ALIGNMENT");
        JButton buttonX3 = new JButton("CENTER_ALIGNMENT");
        
        buttonX1.setAlignmentY(Component.TOP_ALIGNMENT);
        buttonX2.setAlignmentY(Component.BOTTOM_ALIGNMENT);
        buttonX3.setAlignmentY(Component.CENTER_ALIGNMENT);
        
        jpanelX.add(buttonX1);
        jpanelX.add(buttonX2);
        jpanelX.add(buttonX3);

        //添加兩個panel到窗體
        JFrame frame = new JFrame("setAlignmentDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.add(jpanelX);
        frame.add(jpanelY);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);  
    }
}

運行效果如下:

 運行效果圖

那么問題來了,運行結果的對齊方式是反的?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM