2014-01-24 66 views
1

請有人提供一點見解我的代碼。我想讓天平標籤上的按鈕對齊左上角。我曾嘗試不同的佈局管理器,但似乎都導致在中心Java按鈕佈局rightign

public class DefaultView extends JFrame { 

    public DefaultView() {  
     JButton SendBalInc = new JButton(); 
     SendBalInc.setText("Balance");  
     GridBagConstraints c = new GridBagConstraints(); 
     GridBagLayout gridbag = new GridBagLayout(); 
     c.fill = GridBagConstraints.BOTH; 
     // Bal.fill = GridBagConstraints.NONE;  
     JPanel window = new JPanel(); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.setSize(800, 600); 
     // this.setUndecorated(true);  
     window.setBackground(Color.WHITE);  
     JTabbedPane tabbedPane = new JTabbedPane(); 
     tabbedPane.setBackground(Color.WHITE);  
     JComponent panel1 = makeTextPanel("Panel #1"); 
     tabbedPane.addTab("PIN ", panel1);  
     JPanel panel2 = new JPanel(); 
     Box box = Box.createHorizontalBox(); 
     box.add(Box.createHorizontalGlue());  
     box.add(SendBalInc);  
     panel2.setBackground(Color.WHITE);  
     panel2.add(box);  
     tabbedPane.addTab("Balance", panel2);  
     JComponent panel3 = makeTextPanel("Panel #3"); 
     tabbedPane.addTab("Dep", panel3);  
     JComponent panel4 = makeTextPanel("Panel #4"); 
     tabbedPane.addTab("Bill", panel4);  
     window.setLayout(new GridLayout(1, 2)); 
     window.add(tabbedPane);  
     this.add(window);  
    } 

    protected JComponent makeTextPanel(String text) { 
     JPanel panel = new JPanel(); 
     panel.setBackground(Color.WHITE); 
     return panel; 
    }  
} 
+2

是不是'新的FlowLayout(的FlowLayout .LEFT)'在JPanel上設置,然後在'BorderLayout'的另一個'JPanel'的'PAGE_START'位置添加它,爲這種情況工作?一個小的工作示例或預期結果的簡單圖表,將非常感謝,從你身邊:-) –

回答

2

該按鈕是相同或相似的結果,我更喜歡的GridBagLayout:

final JPanel panel2 = new JPanel(); 
    panel2.setLayout(new GridBagLayout()); 
    panel2.setBackground(Color.WHITE); 

    final GridBagConstraints cons = new GridBagConstraints(); 
    cons.weightx = 1D; 
    cons.weighty = 1D; 
    cons.anchor = GridBagConstraints.NORTHWEST; 
    panel2.add(box, cons); 

    tabbedPane.addTab("Balance", panel2); 

注:不需要箱

+0

好吧,所以它在左上角,謝謝。是否有什麼特別的原因,爲什麼你必須使用重量來獲得它在角落和gridx /格力不工作? – user2168435

+0

這在JavaDoc中描述得很好;-) - http://docs.oracle.com/javase/7/docs/api/java/awt/GridBagLayout.html:'用於確定如何分配空間,這對於指定調整大小行爲。除非您爲行(weightx)和列(weighty)中的至少一個組件指定權重,否則所有組件都會聚集在其容器的中心。這是因爲當權重爲零時(默認值),GridBagLayout對象在單元網格和容器邊緣之間放置任何額外的空間。(與GridBagConstraints#weightx相比,更好的描述) – Betlista

0

您可以簡單地使用BoxLayout的

JPanel panel2 = new JPanel(); 
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS)); 
panel2.setBackground(Color.WHITE); 
panel2.add(SendBalInc); 

但我認爲,Betlista的答案w^ith GridBag可能會更好,因爲您有更多的選項可以在未來進一步調整佈局。

0

創建Box並將其直接添加到JTabbedPane,而不是先將其放置在面板中。並且使盒子成爲一個垂直盒子,以便通過在每個孩子上設置setAlignmentX來控制孩子的對齊。

Box box = Box.createVerticalBox(); 
    box.add(SendBalInc); 
    tabbedPane.addTab("Balance", box);