我想创建一个可以帮助我加速GUI设计的特定方法。我使用setBounds
时间最长。现在,我只需要使用FlowLayout或GridLayout,但我不喜欢依赖这些。如何修改JComponents的setBounds方法?
基本上,我正在考虑像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)
那么简单,因为第三个参数感觉效率不高。那么有什么建议?并请使用可理解的术语。
Java Swing设计用于[布局管理器](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html)。看看[Spring布局管理器](https://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html),看看你是否更喜欢使用它。 –