如何优化这种循环?

时间:2014-07-16 20:31:55

标签: java swing loops layout layout-manager

我试图制作这个GUi。

enter image description here
我编写自己的布局,因为现有的布局管理器不符合我的要求 它工作,但我尝试通过使用循环优化所有按钮的创建。

的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));

但有些东西像孩子[i]&#34;的循环一样失踪。我确定有更好的解决方案来改善循环任何改进或建议的想法?感谢

2 个答案:

答案 0 :(得分:3)

  

我编写自己的布局,因为现有的布局管理器不符合我的要求

正确的想法,但您的实施不正确。您需要提供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)前一个按钮上。

这就是应该如何创建布局管理器。您不应该需要复杂的循环来构建添加到面板的每个组件的约束。这是布局管理员的工作。

答案 1 :(得分:1)

你可以尝试:

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));
    }
}