Swing-布局管理器應用--WIN7上計算器的UI實現


學完了Swing布局管理器,為了加深理解我決定做一些UI的實現,那就從WIN7上的計算器開始吧!首先,我們來研究一下它的UI。該計算器的UI主要有3個,分別是標准型、科學型和程序員型,如下圖所示。

 

 

 標准型UI

 

 

科學型UI

 

 

程序員型UI

 

首先分析標准型UI:

 

標准型UI分析

該UI除菜單欄外,分兩部分。考慮到它們在不同的UI中都會復用,我們將其分別使用screenPanel和standardPanel來進行實現。screenPanel沒什么好說的,使用一個按鈕獨占整個面板,並設置按鈕文字右對齊即可。為了實現按鈕的充滿效果,srceenPanel需要使用BorderLayout,並將按鈕位置設置為CENTER。

standardPanel則是標准的GridBagLayout樣式,“MC”按鈕位置為(0,0),“=”按鈕獨占2行1列,“0”按鈕獨占1行2列,其余按鈕各只占1行1列。可以使用一個二維數組來定義這些鍵位,並在for循環中添加這些按鈕。

 

接下來分析科學型UI:

 

科學型UI分析

窗體的整體布局和layout不變,而且顯示部分不變,復用screePanel即可。下部為一個mainPanel,它內含scitificFunctionPanel和standardNumPanel。而scitificFunctionPanel又內含一個angelPanel。mainPanel也采用GridBagLayout,位置分別位於(0,0)和(1,0)。當然也可以采用BorderLayout,這兩個子面板分別放置在WEST和CENTER,那么這樣有一個問題,全屏放大后縮放比例是不一樣的,如下圖:

 

使用BorderLayout時的UI放大效果圖

 

而使用GridBagLayout就可以保證這兩個子面板的縮放是完全平等的,縮放效果如下圖:

 

使用GridBagLayout時的UI放大效果圖

 

 

接下來分析程序員型UI:

 

程序員型UI分析

screenPanel保持不變,而mainPanel這次被划分成3部分,分別是binaryPanel、programFunctionPanel和standardNumPanel。它們分別使用GridBagLayout來實現。

bitPanel的布局分解如下:

 

bitPanel布局分析

整個界面可分割為32個bitPanel;其中,第0、2行的bitPanel由4個label組成(因為每一位數均具有獨立的事件響應);第1、3行的bitPanel只包含1個label。

programFunctionPanel的布局分解如下:

 

programFunctionPanel布局分析

可見,除(0,0)和(0,3)的位置上各為1個占據3行1列的panel外,其余位置均為1個button。Panel內包含4個combobox。

 好啦,到現在所有的布局都分析完畢啦。下面是最終效果圖:

標准型效果

 

標准型放大效果

 

科學型效果

 

科學型放大效果

 

程序員型效果

 

程序員型放大效果

具體的代碼:

CalculatorUI.java

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

/*
 * 主UI
 */
public class CalculatorUI extends JFrame {
    JPanel contentPane;
    private JMenuBar menuBar = new JMenuBar();// 菜單欄
    private JButton screenButton = new JButton("0");// 結果顯示欄
    String[] menuViewItemNames = { "標准型", "科學型", "程序員" };
    String[] menuNames = { "查看", "編輯", "幫助" };

    MenuItemHandler menuItemHandler = new MenuItemHandler();

    public CalculatorUI() {
        // 設置窗體屬性
        setTitle("計算器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 添加菜單欄和菜單
        setJMenuBar(menuBar);
        for (String name : menuNames) {
            JMenu menu = new JMenu(name);
            menuBar.add(menu);
        }

        // “查看”菜單添加菜單項
        for (String name : menuViewItemNames) {
            JMenuItem menuItem = new JMenuItem(name);
            menuItem.addActionListener(menuItemHandler);
            menuBar.getMenu(0).add(menuItem);
        }
    }

    public void setBasicPane() {
        System.out.println("setBasicFrame called");
        // 設為窗體默認面板
        contentPane = new JPanel();
        contentPane.setLayout(new GridBagLayout());
        setContentPane(contentPane);

        // 添加顯示按鈕
        JPanel srceenPanel = new JPanel();
        srceenPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
        srceenPanel.setLayout(new BorderLayout());
        srceenPanel.add(screenButton, BorderLayout.CENTER);
        screenButton.setHorizontalAlignment(SwingConstants.RIGHT);// 文字右對齊

        // 添加顯示面板
        contentPane.add(
                srceenPanel,
                new GBC(0, 0).setFill(GridBagConstraints.BOTH).setWeight(100,
                        100));
    }

    public void setStandardMode() {
        System.out.println("切換到標准型");
        setTitle("計算機-標准型");
        setBasicPane();
        StandardNumPanel standardPanel = new StandardNumPanel();
        getContentPane().add(
                standardPanel,
                new GBC(0, 1).setFill(GridBagConstraints.BOTH).setWeight(100,
                        100));
        showFrame();
    }

    public void setScitificMode() {
        System.out.println("切換到科學型");
        setTitle("計算機-科學型");
        setBasicPane();
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new GridBagLayout());
        ScitificFunctionPanel scitificFunctionPanel = new ScitificFunctionPanel();
        StandardNumPanel standardNumPanel = new StandardNumPanel();
        mainPanel.add(
                scitificFunctionPanel,
                new GBC(0, 0).setFill(GridBagConstraints.BOTH).setWeight(100,
                        100));
        mainPanel.add(
                standardNumPanel,
                new GBC(1, 0).setFill(GridBagConstraints.BOTH).setWeight(100,
                        100));
        getContentPane().add(
                mainPanel,
                new GBC(0, 1).setFill(GridBagConstraints.BOTH).setWeight(100,
                        100));
        showFrame();
    }

    public void setProgramerMode() {
        System.out.println("切換到程序員型");
        setBasicPane();
        setTitle("計算機-程序員型");
        // 添加binaryPanel
        JPanel binaryPanel = new BinaryPanel();
        getContentPane().add(
                binaryPanel,
                new GBC(0, 1).setFill(GridBagConstraints.BOTH).setWeight(100,
                        100).setInsets(5));
        //構造mainPanel,使用ProgramFunctionPanel和StandardNumPanel填充
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new GridBagLayout());
        mainPanel.add(new ProgramFunctionPanel(), new GBC(0,0).setFill(GridBagConstraints.BOTH).setWeight(100,
                        100).setInsets(5));
        mainPanel.add(new StandardNumPanel(), new GBC(1,0).setFill(GridBagConstraints.BOTH).setWeight(100,
                100).setInsets(5));
        //添加mainPanel
        getContentPane().add(
                mainPanel,
                new GBC(0, 2).setFill(GridBagConstraints.BOTH).setWeight(100,
                        100));        
        showFrame();
    }

    public void calculateBinary() {

    }

    public void showFrame() {
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        CalculatorUI frame = new CalculatorUI();
        // frame.setScitificMode();
        frame.setProgramerMode();
        // frame.setStandardMode();
        // frame.setSize(200, 200);
        // frame.setVisible(true);
    }

    class MenuItemHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() instanceof JMenuItem) {
                JMenuItem menuItem = (JMenuItem) e.getSource();
                String name = menuItem.getText();
                if (name != null && name.equals("標准型")) {

                    setStandardMode();
                } else if (name != null && name.equals("科學型")) {
                    setScitificMode();
                } else if (name != null && name.equals("程序員")) {
                    setProgramerMode();
                    // System.out.println("切換到程序員");
                }
            }
        }
    }

    class BitButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() instanceof JButton) {
                JButton button = (JButton) e.getSource();
                String text = button.getText();
                String newText = text.equals("0") ? "1" : "0";
                button.setText(newText);
                // 計算數值並更新顯示屏
                calculateBinary();
            }
        }
    }
}

StandardNumPanel.java

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

public class StandardNumPanel extends JPanel {

    public StandardNumPanel() {
        // 設置窗體layout
        setLayout(new GridBagLayout());

        // add buttons
        String[][] btnStrings = { { "MC", "MR", "MS", "M+", "M-" },
                { "←", "CE", "C", "+-", "sqrt" },
                { "7", "8", "9", "/", "%" }, { "4", "5", "6", "*", "1/x" },
                { "1", "2", "3", "-", "=" }, { "0", "0", ".", "+", "=" } };

        boolean isBtnEqualsNeedsAdded = true;
        boolean isBtnPlusNeedsAdded = true;

        for (int i = 0; i < btnStrings.length; i++) {
            for (int j = 0; j < btnStrings[0].length; j++) {
                if (btnStrings[i][j].equals("=") && isBtnEqualsNeedsAdded) {
                    add(new JButton(btnStrings[i][j]), new GBC(j, i , 1, 2)
                            .setFill(GridBagConstraints.BOTH).setInsets(3)
                            .setWeight(100, 100));
                    isBtnEqualsNeedsAdded = false;
                    continue;
                }
                if (btnStrings[i][j].equals("0") && isBtnPlusNeedsAdded) {
                    add(new JButton(btnStrings[i][j]), new GBC(j, i , 2, 1)
                            .setFill(GridBagConstraints.BOTH).setInsets(3)
                            .setWeight(100, 100));
                    isBtnPlusNeedsAdded = false;
                    continue;
                }
                add(new JButton(btnStrings[i][j]), new GBC(j, i , 1, 1)
                        .setFill(GridBagConstraints.BOTH).setInsets(3)
                        .setWeight(100, 100));
            }
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }
}

ScitificFunctionPanel.java

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class ScitificFunctionPanel extends JPanel {

    public ScitificFunctionPanel() {
        // 設置窗體layout
        setLayout(new GridBagLayout());

        // 用於放置“度”、“弧度”、“梯度”這三個按鈕
        JPanel angelPanel = new JPanel();
        BoxLayout boxLayout = new BoxLayout(angelPanel, BoxLayout.X_AXIS);
        angelPanel.setLayout(boxLayout);
        angelPanel.setBorder(BorderFactory.createEtchedBorder());
        JRadioButton angelButton = new JRadioButton("度");
        JRadioButton radianButton = new JRadioButton("弧度");
        JRadioButton gradientButton = new JRadioButton("梯度");

        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(angelButton);
        buttonGroup.add(radianButton);
        buttonGroup.add(gradientButton);

        angelPanel.add(angelButton);
        angelPanel.add(Box.createHorizontalGlue());
        angelPanel.add(radianButton);
        angelPanel.add(Box.createHorizontalGlue());
        angelPanel.add(gradientButton);

        // 添加角度面板
        add(angelPanel, new GBC(0, 0, 5, 1).setFill(GridBagConstraints.BOTH)
                .setInsets(5).setWeight(100, 100));

        // 添加按鈕
        String[][] btnStrings = { { "", "Inv", "In", "(", ")" },
                { "Int", "sinh", "sin", "x^2", "n!" },
                { "dms", "cosh", "cos", "x^y", "y√x" },
                { "π", "tanh", "tan", "x^3", "3√x" },
                { "F-E", "Exp", "Mod", "log", "10^x" } };

        for (int i = 0; i < btnStrings.length; i++) {
            for (int j = 0; j < btnStrings[0].length; j++) {
                JButton button = new JButton(btnStrings[i][j]);
                add(button,
                        new GBC(j, i + 1, 1, 1)
                                .setFill(GridBagConstraints.BOTH).setInsets(5)
                                .setWeight(100, 100));
                if (i + j == 0)
                    button.setEnabled(false);
            }
        }

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
    }

}

BinaryPanel.java

import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class BinaryPanel extends JPanel{

    List<JPanel> bitPanelList = new ArrayList<JPanel>();
    
    public BinaryPanel(){
        setLayout(new GridBagLayout());
        setBorder(BorderFactory.createEtchedBorder());
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 8; j++) {
                if (i == 0 || i == 2) {
                    // 建立一個面板並設置為左對齊的flowLayout,它容納4個label
                    JPanel bitPanel = new JPanel();
                    FlowLayout flowLayout = new FlowLayout();
                    flowLayout.setAlignment(FlowLayout.LEFT);
                    flowLayout.setHgap(0);
                    bitPanel.setLayout(flowLayout);
                    bitPanel.setName(String.valueOf(bitPanelList.size()));
                    bitPanelList.add(bitPanel);
                    // 添加4個label
                    for (int k = 0; k < 4; k++) {
                        JLabel label = createBitLabel();
                        String buttonName = String.valueOf(k);
                        label.setName(buttonName);
                        //label.setText(buttonName);
                        bitPanel.add(label);
                        System.out.println("add createBitButton of "
                                + buttonName);

                    }
                    // 將包含4個button的小面板作為一個單元格添加到binaryPanel
                    add(bitPanel,
                            new GBC(j, i).setFill(GridBagConstraints.BOTH)
                                    .setWeight(100, 100).setInsets(5));
                } else if (i == 1) {
                    String[] texts = { "63", null, null, null, "47", null,
                            null, "     32" };
                    for (int k = 0; k < texts.length; k++) {
                        JLabel indexLabel = new JLabel();
                        if (texts[k] == null)
                            continue;
                        indexLabel.setText(texts[k]);
                        add(indexLabel,    new GBC(k, i).setFill(GridBagConstraints.BOTH)
                                        .setWeight(100, 100).setInsets(5));
                    }

                } else if (i == 3) {
                    String[] texts = { "31", null, null, null, "15", null,
                            null, "       0" };
                    for (int k = 0; k < texts.length; k++) {
                        JLabel indexLabel = new JLabel();
                        if (texts[k] == null)
                            continue;
                        indexLabel.setText(texts[k]);
                        add(indexLabel,
                                new GBC(k, i).setFill(GridBagConstraints.BOTH)
                                        .setWeight(100, 100).setInsets(5));
                    }
                }
            }
        }
    }
    

    private JButton createBitButton() {
        JButton bitButton = new JButton();
        bitButton.setText("0");
        bitButton.setEnabled(false);
        return bitButton;
    }

    private JLabel createBitLabel() {
        JLabel bitLabel = new JLabel();
        bitLabel.setText("0");

        // bitLabel.setEnabled(false);
        return bitLabel;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new BinaryPanel());
        frame.pack();
        frame.setVisible(true);
    }

}

ProgramFunctionPanel.java

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;


public class ProgramFunctionPanel extends JPanel{

    public ProgramFunctionPanel(){
        // 設置窗體layout
        setLayout(new GridBagLayout());
        add(createRadixPanel(), new GBC(0,0, 1, 3).setWeight(100, 100).setFill(GridBagConstraints.BOTH));        
        add(createBytePanel(), new GBC(0,3, 1, 3).setWeight(100, 100).setFill(GridBagConstraints.BOTH));
        
        String textString [][] = {
                {null, "", "Mod","A"}, 
                {null, "(", ")","B"},
                {null, "RoL", "RoR","C"},
                {null, "Or", "Xor","D"},
                {null, "Lsh", "Rsh","E"},
                {null, "Not", "And","F"},};
        
        for (int i = 0; i< textString.length; i++) {
            for (int j = 0; j< textString[i].length; j++) {
                String text = textString[i][j];
                if(text != null){
                    JButton button = new JButton(text);
                    if(text.equals(""))
                        button.setEnabled(false);
                    add(button, new GBC(j, i).setWeight(100, 100).setFill(GridBagConstraints.BOTH).setInsets(5));
                    //System.out.printf("add btn at (%d,%d)\n", j,i);
                }
            }
        }
    }
    
    private JPanel createRadixPanel()
    {
        JPanel radixPanel = new JPanel();
        
        BoxLayout boxLayout=new BoxLayout(radixPanel, BoxLayout.Y_AXIS); 
        radixPanel.setLayout(boxLayout);
        radixPanel.setBorder(BorderFactory.createEtchedBorder());
        String [] radixStrings = {"十六進制", "十進制","八進制","二進制"};    
        ButtonGroup btnGroup = new ButtonGroup();
        for (String radixString : radixStrings) {
            JRadioButton radioButton = new JRadioButton(radixString);
            //注冊事件
            btnGroup.add(radioButton);
            radixPanel.add(radioButton);            
        }
        return radixPanel;
    }
    
    private JPanel createBytePanel()
    {
        JPanel bytePanel = new JPanel();
        BoxLayout boxLayout=new BoxLayout(bytePanel, BoxLayout.Y_AXIS); 
        bytePanel.setLayout(boxLayout);
        bytePanel.setBorder(BorderFactory.createEtchedBorder());
        String [] byteStrings = {"四字", "雙字","字","字節"};    
        ButtonGroup btnGroup = new ButtonGroup();
        for (String byteString : byteStrings) {
            JRadioButton radioButton = new JRadioButton(byteString);
            //注冊事件
            btnGroup.add(radioButton);
            bytePanel.add(radioButton);            
        }
        return bytePanel;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ProgramFunctionPanel());
        frame.pack();
        frame.setVisible(true);
    }

}

 

GBC.java
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

/*
 * GBC.java,source code from java核心技術 卷1 基礎知識,P381
 */

public class GBC extends GridBagConstraints{
/*
 * constructs a GBC with a given gridx and gridy position and all other grid
 * bag constraint values set to the default
 * @param gridx the gridx position
 * @param gridy the gridy position
 */
    public GBC(int gridx, int gridy){
        this.gridx = gridx;
        this.gridy = gridy;
    }
    
    public GBC(int gridx, int gridy, int gridWidth, int gridHeight){
        this.gridx = gridx;
        this.gridy = gridy;
        this.gridwidth = gridWidth;
        this.gridheight = gridHeight;
    }
    
    /*
     * sets the anchor
     * @param anchor the anchor style
     * @return this object for further modification
     */
    
    public GBC setAnchor(int anchor){
        this.anchor = anchor;
        return this;
    }
    
    /*
     * sets the fill direction
     * @param fill the fill direction
     * @return this object for further modification
     */
    
    public GBC setFill(int fill){
        this.fill = fill;
        return this;
    }
    
    /*
     * sets the cell weights
     * @param weightx the cell weight in x direction
     * @param weighty the cell weight in y direction
     * @return this object for further modification
     */
    
    public GBC setWeight(int weightx, int weighty){
        this.weightx = weightx;
        this.weighty = weighty;
        return this;
    }
    
    /*
     * sets the insets of this cell
     * @param insets distance ths spacing to use in all directions
     * @return this object for further modification
     */
    
    public GBC setInsets(int distance){
        this.insets = new Insets(distance, distance, distance, distance);
        return this;
    }
    
    /*
     * sets the insets of this cell
     * @param top distance ths spacing to use on top
     * @param bottom distance ths spacing to use on bottom
     * @param left distance ths spacing to use to the left
     * @param right distance ths spacing to use to the  right
     * @return this object for further modification
     */
    
    public GBC setInsets(int top, int left,int bottom,int right){
        this.insets = new Insets(top, left, bottom, right);
        return this;
    }
    
    /*
     * sets the Ipad of this cell
     * @param Ipad distance ths spacing to use in all directions
     * @return this object for further modification
     */
    
    public GBC setIpad(int ipadx, int ipady){
        this.ipadx = ipadx;
        this.ipadx = ipadx;
        return this;
    }
}

 


免責聲明!

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



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