2015-02-23 48 views
1

我正在使用BorderLayout作爲我的應用程序。 setLayout(new BorderLayout()); 我需要在JPanel"NORTH"的左邊和右邊對齊兩個JLabels將「左」和右兩個JLabels對齊到「North」BorderLayout中

這裏是我的代碼:

JPanel top = new JPanel(); 
top.add(topTxtLabel); 
top.add(logoutTxtLabel); 
add(BorderLayout.PAGE_START, top); 

所以我需要topTxtLabel在左,logoutTxtLabel右。 我試圖再次實施邊界佈局使用「西部」和「東部」,但它沒有奏效。想法?

回答

2

假設你的應用程序由JFrameBorderLayout你可以試試這個:重新設置您的JPanel的佈局模式BorderLayout。在框架的北部添加面板。然後在東部和西部添加2 JLabels。您也可以將JFrame替換爲另一個JPanel

import java.awt.BorderLayout; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 


public class Main 
{ 

    public static void main(String[] args) 
    { 
     new Main(); 
    } 

    Main() 
    { 
     JFrame frame = new JFrame("MyFrame"); 
     frame.setLayout(new BorderLayout()); 

     JPanel panel = new JPanel(new BorderLayout()); 
     JLabel left = new JLabel("LEFT"); 
     JLabel right = new JLabel("RIGHT"); 
     JPanel top = new JPanel(new BorderLayout()); 

     top.add(left, BorderLayout.WEST); 
     top.add(right, BorderLayout.EAST); 
     panel.add(top, BorderLayout.NORTH); 
     frame.add(panel, BorderLayout.NORTH); 
     frame.add(new JLabel("Another dummy Label"), BorderLayout.SOUTH); 

     frame.pack(); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} 
+0

正如我所說,我試圖將BorderLayout WEST和EAST結合在一個主要的JPanel NORTH中,並且它沒有工作......任何其他想法? :( – 2015-02-23 14:55:04

+0

它適用於我(請參閱我的編輯)。這就是我對你的問題的解釋。如果你打算採取不同的行爲,那麼請具體說明你需要什麼。 – BluesSolo 2015-02-23 15:16:02