2016-10-03 30 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