簡體   English   中英

如何優化這種循環?

[英]How to optimize this kind of loop?

我正在嘗試制作這個GUI。

在此處輸入圖片說明
我編寫自己的布局是因為現有的布局管理器無法滿足我的要求。它可以工作,但是我嘗試通過使用循環來優化所有按鈕的創建。

的Test.class

public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        JPanel parent = new JPanel();
        f.add(parent);
        parent.setLayout(new BoxLayout(parent, BoxLayout.X_AXIS));

        JPanel[] children = new JPanel[6];
        for (int i = 1; i < children.length; i++) {
            children[i] = new JPanel();
            children[i].setLayout(new XYLayout());
            children[i].setBorder(new LineBorder(Color.red));
            parent.add(children[i]);
        }

        int x = 0, y = 375, w = 0, h = 50;

        children[1].add(new JButton("8"), new XYConstraints(0, 25, 0, 50));
        children[1].add(new JButton("7"), new XYConstraints(0, 75, 0, 50));
        children[1].add(new JButton("6"), new XYConstraints(0, 125, 0, 50));
        children[1].add(new JButton("5"), new XYConstraints(0, 175, 0, 50));
        children[1].add(new JButton("4"), new XYConstraints(0, 225, 0, 50));
        children[1].add(new JButton("3"), new XYConstraints(0, 275, 0, 50));
        children[1].add(new JButton("2"), new XYConstraints(0, 325, 0, 50));
        children[1].add(new JButton("1"), new XYConstraints(0, 375, 0, 50));

        children[2].add(new JButton("7"), new XYConstraints(240, 25, 0, 100));
        children[2].add(new JButton("6"), new XYConstraints(200, 75, 0, 100));
        children[2].add(new JButton("5"), new XYConstraints(160, 125, 0, 100));
        children[2].add(new JButton("4"), new XYConstraints(120, 175, 0, 100));
        children[2].add(new JButton("3"), new XYConstraints(80, 225, 0, 100));
        children[2].add(new JButton("2"), new XYConstraints(40, 275, 0, 100));
        children[2].add(new JButton("1"), new XYConstraints(0, 325, 0, 100));

        children[3].add(new JButton("6"), new XYConstraints(200, 25, 0, 150));
        children[3].add(new JButton("5"), new XYConstraints(160, 75, 0, 150));
        children[3].add(new JButton("4"), new XYConstraints(120, 125, 0, 150));
        children[3].add(new JButton("3"), new XYConstraints(80, 175, 0, 150));
        children[3].add(new JButton("2"), new XYConstraints(40, 225, 0, 150));
        children[3].add(new JButton("1"), new XYConstraints(0, 275, 0, 150));

        //children[4],//children[5]...



        f.setSize(800, 600);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);

    }

一個文件中的自定義布局:XYLayout

 public class XYLayout implements LayoutManager2, Serializable {

    private int width;
    private int height;
    Hashtable<Component, Object> info;
    static final XYConstraints defaultConstraints = new XYConstraints();

    public XYLayout() {
        info = new Hashtable<Component, Object>();
    }

    public XYLayout(int width, int height) {
        info = new Hashtable<Component, Object>();
        this.width = width;
        this.height = height;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("XYLayout [width=").append(width).append(", height=").append(height).append("]");
        return builder.toString();
    }

    public void addLayoutComponent(String s, Component component1) {
    }

    public void removeLayoutComponent(Component component) {
        info.remove(component);
    }

    public Dimension preferredLayoutSize(Container target) {
        return getLayoutSize(target, true);
    }

    public Dimension minimumLayoutSize(Container target) {
        return getLayoutSize(target, false);
    }

    public void layoutContainer(Container target) {
        Insets insets = target.getInsets();
        int count = target.getComponentCount();
        for (int i = 0; i < count; i++) {
            Component component = target.getComponent(i);
            if (component.isVisible()) {
                Rectangle r = getComponentBounds(component, true);
                component.setBounds(insets.left + r.x, insets.top + r.y, r.width, r.height);
            }
        }

    }

    public void addLayoutComponent(Component component, Object constraints) {
        if (constraints instanceof XYConstraints)
            info.put(component, constraints);
    }

    public Dimension maximumLayoutSize(Container target) {
        return new Dimension(0x7fffffff, 0x7fffffff);
    }

    public float getLayoutAlignmentX(Container target) {
        return 0.5F;
    }

    public float getLayoutAlignmentY(Container target) {
        return 0.5F;
    }

    public void invalidateLayout(Container container) {
    }

    public Rectangle getComponentBounds(Component component, boolean doPreferred) {
        XYConstraints constraints = (XYConstraints) info.get(component);
        if (constraints == null)
            constraints = defaultConstraints;
        Rectangle r = new Rectangle(constraints.getX(), constraints.getY(), constraints.getW(), constraints.getH());
        if (r.width <= 0 || r.height <= 0) {
            Dimension d = doPreferred ? component.getPreferredSize() : component.getMinimumSize();
            if (r.width <= 0)
                r.width = d.width;
            if (r.height <= 0)
                r.height = d.height;
        }
        return r;
    }

    public Dimension getLayoutSize(Container target, boolean doPreferred) {
        Dimension dim = new Dimension(0, 0);
        if (width <= 0 || height <= 0) {
            int count = target.getComponentCount();
            for (int i = 0; i < count; i++) {
                Component component = target.getComponent(i);
                if (component.isVisible()) {
                    Rectangle r = getComponentBounds(component, doPreferred);
                    dim.width = Math.max(dim.width, r.x + r.width);
                    dim.height = Math.max(dim.height, r.y + r.height);
                }
            }

        }
        if (width > 0)
            dim.width = width;
        if (height > 0)
            dim.height = height;
        Insets insets = target.getInsets();
        dim.width += insets.left + insets.right;
        dim.height += insets.top + insets.bottom;
        return dim;
    }

}

class XYConstraints implements Cloneable, Serializable {

    private int x;

    private int y;

    private int w;

    private int h;

    public XYConstraints() {
        this(0, 0, 0, 0);
    }

    public XYConstraints(int x, int y, int w, int h) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getW() {
        return w;
    }

    public void setW(int w) {
        this.w = w;
    }

    public int getH() {
        return h;
    }

    public void setH(int h) {
        this.h = h;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + h;
        result = prime * result + w;
        result = prime * result + x;
        result = prime * result + y;
        return result;
        // return x ^ y * 37 ^ w * 43 ^ h * 47;
    }

    public boolean equals(Object that) {
        if (that instanceof XYConstraints) {
            XYConstraints other = (XYConstraints) that;
            return other.x == x && other.y == y && other.w == w && other.h == h;
        } else {
            return false;
        }
    }

    public Object clone() {
        return new XYConstraints(x, y, w, h);
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("XYConstraints [x=").append(x).append(", y=").append(y).append(", w=").append(w).append(", h=").append(h).append("]");
        return builder.toString();
    }

我的第一次嘗試是:

     for (y = 375; y > 0; y = y - 50)
     children[1].add(new JButton("1"), new XYConstraints(x, y, w, h));

     for (y = 325, x = 0; y > 0 && x < 280; y = y - 50, x = x + 40)
     children[2].add(new JButton("2"), new XYConstraints(x, y, w, 2 * h));

     for (y = 275, x = 0; y > 0 && x < 240; y = y - 50, x = x + 40)
     children[3].add(new JButton("3"), new XYConstraints(x, y, w, 3 * h));

但是缺少諸如“ children [i]”的循環之類的東西。我確定有更好的解決方案來改善循環是否有任何改進或建議的想法? 謝謝

我寫自己的布局是因為現有的布局管理器不符合我的要求

正確的主意,但您的實現不正確。 您需要提供x / y值這一事實意味着您不使用布局管理器,而只是對一些值進行硬編碼。

相反,您需要向布局管理器提供信息以定義布局的參數,可能類似於:

MyLayout layout = new MyLayout(xSize, ySize, xOffset, yOffset);

因此,對於第一個面板,您將使用:

MyLayout layout = new MyLayout(50, 50, 0, 50);

該代碼將說每個分量是(50,50)。 在向面板添加組件時,將x偏移量更改為0,將y offset更改為-50。

您知道您有8個按鈕,因此可以使用數學計算出面板的寬度/高度。 然后,您可以在布局管理器中使用循環來放置每個組件。

所以現在您將組件添加到面板中,如下所示:

panel.add( new JButton("1") );
panel.add( new JButton("2") );
panel.add( new JButton("3") );

對於第二個面板,您可以使用:

MyLayout layout = new MyLayout(50, 100, 50, 50);

因此這一次意味着每個已知按鈕的大小為(50,100),並且每個按鈕都放置到上一個按鈕(50,-50)處。

這就是應該創建布局管理器的方式。 您不需要復雜的循環來構建添加到面板的每個組件的約束。 那是布局管理器的工作。

您可以嘗試:

for( int i=1; i<=3; i++ ) {
    x = 0;
    for( y=375-((i-1)*50; y>0; y-=50, x+=40 ) {
        children[i].add(new JButton((String)i), new XYConstraints(x, y, w, i*h));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM