如何修改JComponents的setBounds方法?

时间:2016-10-03 09:41:29

标签: java swing parameter-passing jcomponent setbounds

我希望创建一种可以帮助我加快GUI设计速度的方法。我使用setBounds的时间最长。现在,我会选择FlowLayout或GridLayout,但我不想依赖那些。

基本上,我正在考虑像placeAbove这样的方法,它将JComponent置于另一个JComponent之上。它的参数将是参考点JComponent和它们彼此距离的整数。我目前在以下方面取得了成功:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class BoundBender extends JFrame {
    public BoundBender() {
        Container c = getContentPane();
        c.setLayout(null);

        JLabel l1 = new JLabel("Reference Point");
        JLabel l2 = new JLabel("Above Label");
        JLabel l3 = new JLabel("Below Label");
        JLabel l4 = new JLabel("Before Label");
        JLabel l5 = new JLabel("After Label");

        c.add(l1);
        l1.setBounds(170, 170, 100, 20);
        c.add(l2);
        placeAbove(l1, 0, l2);
        c.add(l3);
        placeBelow(l1, 10, l3);
        c.add(l4);
        placeBefore(l1, 20, l4);
        c.add(l5);
        placeAfter(l1, 30, l5);

        setVisible(true);
        setSize(500, 500);
    }
    public static void main (String args[]) {
        BoundBender bb = new BoundBender();
        bb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void placeAbove(JComponent j, int a, JComponent k) {
        int x= j.getX();
        int y= j.getY();
        int w= j.getWidth();
        int h= j.getHeight();

        y=(y-h)-a;

        k.setBounds(x, y, w, h);
    }
    public static void placeBelow(JComponent j, int a, JComponent k) {
        int x= j.getX();
        int y= j.getY();
        int w= j.getWidth();
        int h= j.getHeight();

        y=y+h+a;

        k.setBounds(x, y, w, h);
    }
    public static void placeBefore(JComponent j, int a, JComponent k) {
        int x= j.getX();
        int y= j.getY();
        int w= j.getWidth();
        int h= j.getHeight();

        x=(x-w)-a;

        k.setBounds(x, y, w, h);
    }
    public static void placeAfter(JComponent j, int a, JComponent k) {
        int x= j.getX();
        int y= j.getY();
        int w= j.getWidth();
        int h= j.getHeight();

        x=x+w+a;

        k.setBounds(x, y, w, h);
    }
}

但是,我想让它像l2.placeAbove(l1, 0)一样简单,因为第三个参数感觉效率低下。那有什么建议吗?请使用可理解的术语。

1 个答案:

答案 0 :(得分:0)

然后使用其返回值。而不是void返回Rectangle的实例。它看起来像是:

    public static Rectangle placeAbove(JComponent j, int a) {
    int x= j.getX();
    int y= j.getY();
    int w= j.getWidth();
    int h= j.getHeight();

    y=(y-h)-a;

    //return our new bounds projected in a Rectangle Object
    return new Rectangle(x, y, w, h); 
}

然后用例将设置边界矩形:

k.setBounds(placeAbove(j, a));

这样就可以在JComponent中使用从java.awt.Component继承的setBounds(Rectangle r)

希望这有帮助!