Java组件对齐到左上角

时间:2014-01-09 20:59:33

标签: java swing layout jcomponent

我想将我的两个组件对齐到窗口的左上角。

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

public class MainFrame extends JFrame {
    public MainFrame() {
    JPanel mainPanel = new JPanel(new BorderLayout());
    JPanel gridbagPanel = new JPanel();
    this.setLayout(new BorderLayout());

    gridbagPanel.setLayout(new GridBagLayout());
    GridBagConstraints gc = new GridBagConstraints();

    JLabel nameLabel = new JLabel(player.getName());
    nameLabel.setHorizontalAlignment(SwingConstants.CENTER);
    nameLabel.setFont(new Font("Serif",Font.PLAIN,24));
    mainPanel.add(nameLabel, BorderLayout.NORTH);

    JLabel money = new JLabel("Pinigai: "+new Integer(player.getMoney()).toString());
    gc.gridx = 0;
    gc.gridy = 0;
    gc.anchor = GridBagConstraints.PAGE_START;
    gc.insets = new Insets(2,0,0,2);
    gridbagPanel.add(money,gc);

    JLabel job = new JLabel("Darbas: "+new Integer(player.getSkin()).toString());
    gc.gridx = 0;
    gc.gridy = 1;
    gc.insets = new Insets(2,0,0,2);
    gc.anchor = GridBagConstraints.LINE_START;
    gridbagPanel.add(job, gc);

    mainPanel.setBorder(new EmptyBorder(10,10,10,10));
    mainPanel.add(gridbagPanel,BorderLayout.WEST);

    add(mainPanel);
    getContentPane().revalidate();
}

} 它目前看起来像这样:Current view of the components

我希望左上角有数字的行。

请注意,我知道JFrame(“this”类)和mainPanel都在使用BorderLayouts。

另一个不相关的问题:我应该何时创建新的GridBagConstraints对象?为什么我不能只将一个存储在私有实例变量中以满足所有用途?

2 个答案:

答案 0 :(得分:4)

GridBagLayout的美妙之处在于列/行大小不固定(即,并非每行/列都必须具有相同的大小,如GridLayout中所示)

你可以“鼓励”某些组件在其给定区域内占据更多空间,而不是其他组件。

weightxweighty之类的内容描述了行/列应占用的可用空间量。添加NORTHWEST anchor约束,您应该开始看到所需的效果。

enter image description here

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class MainFrame extends JFrame {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new MainFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public MainFrame() {
        JPanel mainPanel = new JPanel(new BorderLayout());
        JPanel gridbagPanel = new JPanel();
        this.setLayout(new BorderLayout());

        gridbagPanel.setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();

        JLabel nameLabel = new JLabel("Bebras");
        nameLabel.setHorizontalAlignment(SwingConstants.CENTER);
        nameLabel.setFont(new Font("Serif", Font.PLAIN, 24));
        mainPanel.add(nameLabel, BorderLayout.NORTH);

        JLabel money = new JLabel("Pinigai: " + new Integer(66484).toString());
        gc.gridx = 0;
        gc.gridy = 0;
        gc.anchor = GridBagConstraints.NORTHWEST;
        gc.insets = new Insets(2, 0, 0, 2);
        gridbagPanel.add(money, gc);

        JLabel job = new JLabel("Darbas: " + new Integer(126).toString());
        gc.gridx = 0;
        gc.gridy = 1;
        gc.insets = new Insets(2, 0, 0, 2);
        gc.anchor = GridBagConstraints.NORTHWEST;
        gc.weightx = 1;
        gc.weighty = 1;
        gridbagPanel.add(job, gc);

        mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        mainPanel.add(gridbagPanel, BorderLayout.WEST);

        add(mainPanel);
        getContentPane().revalidate();

    }
}

通常,我会在组件中添加一个“填充”组件,使用它将所有其他组件推送到我想要的位置,但这将归结为您想要实现的目标。

请查看How to use GridBagLayout了解详情

答案 1 :(得分:2)

我更喜欢Box Layouts的粉丝来实现摇摆中的这种静态定位。见下面的例子:

import java.awt.Dimension;

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

public class main extends JFrame {

public static void main(String[] args) throws InterruptedException {
    main m = new main();
    m.setVisible(true);
}

public main() {
    // setup stuff
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setBounds(100, 100, 500, 500);

    // this is the panel I will add to the frame
    JPanel innerPanel = new JPanel();
    // give it a Y axis to stuff is added top to bottom
    innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS));

    // this is a temp panel ill used to add the labels
    JPanel tPanel = new JPanel();
    // its an x axis to add stuff left to right
    tPanel.setLayout(new BoxLayout(tPanel, BoxLayout.X_AXIS));

    // create and add a label to the temp panel
    JLabel label = new JLabel("Some text");
    tPanel.add(label);
    // use our stretchy glue to fill the space to the right of the label
    tPanel.add(Box.createHorizontalGlue());

    // add the temp panel to the inner panel
    innerPanel.add(tPanel);
    // create a spacer with 0 width and 10 height
    innerPanel.add(Box.createRigidArea(new Dimension(0, 10)));

    // reinitialize the temp panel for another label
    tPanel = new JPanel();
    tPanel.setLayout(new BoxLayout(tPanel, BoxLayout.X_AXIS));
    label = new JLabel("Some other text");
    // add the other label to the temp panel
    tPanel.add(label);
    // more stretchy glue
    tPanel.add(Box.createHorizontalGlue());

    // add the temp panel
    innerPanel.add(tPanel);
    // add verticle stretchy glue to fill the rest of the space below the
    // labels
    innerPanel.add(Box.createVerticalGlue());

    // add to the frame
    this.add(innerPanel);
}

}