2015-03-13 113 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是在顶部。