2015-03-13 114 views
1

試圖瞭解用於Java的GridBagLayout是如何工作的。以前從未使用過,所以它可能是我犯的一個愚蠢的錯誤。GridBagLayout沒有得到預期的結果

我的目標是將JLabel放在頁面的頂部中心。我一直在使用Oracle上的java教程,但沒有運氣。看起來標籤仍然在頁面的中心。 (中心在x和y圖的死點)。

從我的理解,如果我設置了gridxgridy約束0,編譯器會頂一下,該計劃的第一行和他們的文本。然後,我使用PAGE START錨點將文本放置在頁面的中心。我不完全確定weightxweighty函數在我的防守中有什麼作用。

import javax.swing.*; 
import java.awt.*; 

class test 
{ 
    public static void main (String Args []) 
    { 
    //frame and jpanel stuff 
    JFrame processDetail = new JFrame("Enter information for processes"); 
    JPanel panelDetail = new JPanel(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 

    //label to add on top centre 
    JLabel label = new JLabel("LOOK AT ME"); 

    //set size of frame and operation 
    processDetail.setSize(500,500); 
    processDetail.setDefaultCloseOperation(processDetail.EXIT_ON_CLOSE); 

    //add the label to panel 
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.anchor = GridBagConstraints.PAGE_START; 
    c.weightx = 0; //not sure what this does entirely 
    c.gridx = 0; //first column 
    c.gridy = 0; //first row 
    panelDetail.add(label, c); 

    processDetail.add(panelDetail); 
    processDetail.setVisible(true); 
    } 
} 
+0

顯示您想要實現的目標以及目前正在獲取的內容的圖像。 – 2015-03-13 16:26:05

回答

2

你只是使用容器向GBL添加一件東西,所以它將居中。如果您在JLabel下添加第二個組件,則JLabel將顯示在頂部。例如,

import java.awt.Dimension; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 

import javax.swing.*; 

public class Test2 { 
    private static void createAndShowGui() { 
     JPanel mainPanel = new JPanel(new GridBagLayout()); 
     GridBagConstraints gbc = new GridBagConstraints(); 
     gbc.gridx = 0; 
     gbc.gridy = 0; 
     gbc.gridheight = 1; 
     gbc.gridwidth = 1; 
     gbc.weightx = 1.0; 
     gbc.weighty = 1.0; 
     gbc.fill = GridBagConstraints.BOTH; 
     gbc.anchor = GridBagConstraints.PAGE_START; 

     mainPanel.add(new JLabel("Look at me!", SwingConstants.CENTER), gbc); 


     gbc.gridy = 1; 
     gbc.gridheight = 10; 
     gbc.gridwidth = 10; 

     mainPanel.add(Box.createRigidArea(new Dimension(400, 400)), gbc); 

     JFrame frame = new JFrame("Test2"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 

我自己,我會使用BorderLayout的,如果我想我的JLabel是在頂部。