1

请看下面的代码

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

public class TestForm extends JFrame
{
    private JLabel firstLabel, secondLabel;

    private JTextField firstTxt, secondTxt;

    private GridBagLayout mainLayout = new GridBagLayout();
    private GridBagConstraints mainCons = new GridBagConstraints();
    private JPanel centerPanel;

      public TestForm()
      {
          this.setLayout(mainLayout);
        //Declaring instance variables  
        firstLabel = new JLabel("First: ");
        secondLabel = new JLabel("Second: ");

        firstTxt = new JTextField(7);
        secondTxt = new JTextField(7);


        mainCons.anchor = GridBagConstraints.WEST;
        mainCons.weightx = 1;
        mainCons.gridy = 2;
        mainCons.gridx = 1;
        mainCons.insets = new Insets(15, 0, 0, 0);
        this.add(createCenterPanel(), mainCons);

        System.out.println("Center Panel Width: "+centerPanel.getWidth());        
        this.setTitle("The Test Form");
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    }

    private JPanel createCenterPanel()
    {
        centerPanel = new JPanel();

        GridBagLayout gbl = new GridBagLayout();
        GridBagConstraints gbc = new GridBagConstraints();

        centerPanel.setLayout(gbl);

        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(15,0,0,0);
        centerPanel.add(firstLabel,gbc);

        gbc.gridx = 2;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(15,0,0,0);
        centerPanel.add(firstTxt,gbc);

        gbc.gridx = 3;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(15,10,0,0);
        centerPanel.add(secondLabel,gbc);

        gbc.gridx = 4;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(15,-10,0,0);
        centerPanel.add(secondTxt,gbc);


        centerPanel.setBorder(BorderFactory.createTitledBorder("The Testing Form"));
        centerPanel.setPreferredSize(centerPanel.getPreferredSize());
        centerPanel.validate();

        System.out.println("Width is: "+centerPanel.getWidth());
        System.out.println("Width is: "+centerPanel.getHeight());

        return centerPanel;

    }


    public static void main(String[]args)
    {
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            new TestForm();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

我正在尝试获取centerPanel2 个位置的宽度。但在这两种情况下,我都得到 0 作为答案!我必须以某种方式获取宽度和高度,因为 southPanel(此处未包括)将使用这些值,其中一些会降低到高度。请帮忙!

4

1 回答 1

4

pack()在或被setSize()调用之前宽度为0 。pack()您可以在调用后获取宽度并使用它

或者

定义你自己的LayoutManager使用宽度作为另一个布局部分的高度(southPanel)

于 2013-01-08T16:48:05.107 回答