我希望创建一种可以帮助我加快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)
一样简单,因为第三个参数感觉效率低下。有什么建议吗?请使用通俗易懂的术语
则使用其返回值。而不是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)
。
希望这对你有帮助!