2016-10-03 67 views
1

我想创建一个可以帮助我加速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)那么简单,因为第三个参数感觉效率不高。那么有什么建议?并请使用可理解的术语。

+0

Java Swing设计用于[布局管理器](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html)。看看[Spring布局管理器](https://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html),看看你是否更喜欢使用它。 –

回答

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

这样,你使用来自java.awt.Component在JComponent中继承了setBounds(Rectangle r)

希望这会有所帮助!

+1

我有点希望我不再需要使用setBounds ...非常感谢,因为这帮助我更好地理解了Rectangle类。 :) – ArcIX