简体   繁体   English

Java GridBagLayout组件定位

[英]Java GridBagLayout components positioning

I'm trying to make a simple layout where the labels are next to the buttons and close. 我正在尝试制作一个简单的布局,其中标签位于按钮旁边并关闭。 Here is the order I am adding them: 这是我添加它们的顺序:

add(label_1, cons);

cons.gridx = 1;
add(textArea,cons);

cons.gridx = 0;
cons.gridy = 2;
add(button_1,cons);

cons.gridx= 0;
cons.gridy = 4;
add(button_2,cons);

cons.gridx=0;
cons.gridy=6;
add(button_3,cons);

cons.gridx = 1;
cons.gridy = 2;
add(label_2, cons);       

cons.gridy=4;
add(label_3,cons);

cons.gridy=6;
add(label_4,cons);

Which looks like this: 看起来像这样:

在此处输入图片说明

I just need the labels positioned closer to the buttons, but it seems the closest x value I can give them is 1, it seems relatively positioned - is there a way I could absolutely position them? 我只需要将标签放置在靠近按钮的位置,但似乎我可以给它们提供的最接近的x值是1,似乎是相对放置的-是否可以绝对定位它们?

You have several options available to you, depending on how you want this to look like, all explained in the already posted tutorial . 您可以根据自己的需要选择几个选项,所有选项都在已发布的教程中进行了说明。

  1. Set the fill field of the constraints to HORIZONTAL and alignment of the labels to WEST (Or LINE_START , whichever you're used to), along with a positive weightx. 将约束的fill字段设置为HORIZONTAL ,将标签的对齐设置为WEST (或LINE_START ,以您LINE_START为准),以及正权重x。 This will make both the labels and buttons occupy all available horizontal space, and their alignment will mean the text will be on the left edge. 这将使标签和按钮都占据所有可用的水平空间,并且它们的对齐将意味着文本将在左侧。
  2. Use the anchor field. 使用anchor字段。 This controls where a smaller component would be located in it's cell - you likely want a right or central alignment for the buttons, and left for the labels. 这可以控制较小的组件在其单元格中的放置位置-您可能希望按钮的向右或居中对齐,标签的向左对齐。
  3. If you want the labels to be close to the buttons without anything changing size, then a grid will not serve you very well, since the "Enter a sentence" field is too long. 如果您希望标签靠近按钮而不改变大小,那么网格将不能很好地为您服务,因为“输入句子”字段太长。 You may want to have 2 different panels for the top and bottom ( BorderLayout much?), or a more intelligent layout manager 您可能希望顶部和底部有2个不同的面板(很多BorderLayout吗?),或更聪明的布局管理器

在此处输入图片说明

The window above was produced with the code below, which uses 3 external classes. 上面的窗口是使用下面的代码生成的,该代码使用3个外部类。

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class GridBagLayout{

  JFrame      frame;

  public GridBagLayout() {
    initComponents();
  }

  private void initComponents(){
    JTextField  text  = new JTextField("",10);
    JButton     but1  = new JButton("button 1");
    JButton     but2  = new JButton("button 2");
    JButton     but3  = new JButton("button 3");
    JLabel      lab0  = new JLabel("Enter a sentence");
    JLabel      lab1  = new JLabel("test 1");
    JLabel      lab2  = new JLabel("test 2");
    JLabel      lab3  = new JLabel("test 3");

    frame  = new JFrame("TestGridBagLayout");
    frame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    frame.setLayout(new java.awt.GridBagLayout());

    frame.add(lab0,   new GBConstraints(0,0));
    frame.add(text,   new GBConstraints(1,0));

    frame.add(but1,   new GBConstraints(0,1));
    frame.add(lab1,   new GBConstraints(1,1));

    frame.add(but2,   new GBConstraints(0,2));
    frame.add(lab2,   new GBConstraints(1,2));

    frame.add(but3,   new GBConstraints(0,3));
    frame.add(lab3,   new GBConstraints(1,3));

    frame.setVisible(true);
    frame.pack();
  }  

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

The window below was produced by changing the new GBConstraints lines above to the lines shown below the picture, the point being that there are several fairly easy ways to tweak the layout to make it look just the way you want--how close together and how vertically aligned, for two issues. 下面的窗口是通过将上方的new GBConstraints行更改为图片下方显示的行而产生的,要点是,有几种相当简单的方法可以调整布局,使其看起来像您想要的样子-紧密程度以及垂直对齐,有两个问题。

在此处输入图片说明

frame.add(lab0,   new GBConstraints(0,0).anchor(EAST));
frame.add(text,   new GBConstraints(1,0).ipad(100, 0).anchor(WEST));

frame.add(but1,   new GBConstraints(0,1));
frame.add(lab1,   new GBConstraints(1,1));

frame.add(but2,   new GBConstraints(0,2));
frame.add(lab2,   new GBConstraints(1,2).insets(15, -15, 5, 5));

frame.add(but3,   new GBConstraints(0,3).anchor(EAST));
frame.add(lab3,   new GBConstraints(1,3).anchor(WEST));

Note that the second line above has two constraints added onto the GBConstraint; 注意,上面的第二行在GBConstraint上添加了两个约束。 the flexibility is provided by classes Fill , Anchor , and GBConstraints that were provided by @SplungeBob in this thread . 灵活性由@SplungeBob在此线程中提供的类FillAnchorGBConstraints提供。

Try to play with the following properties of GridBagConstraints: gridheight and weighty. 尝试使用GridBagConstraints的以下属性:gridheight和weighty。 I would try to modify this part of your code: 我会尝试修改您的代码的这一部分:

cons.gridx = 1;
cons.gridy = 2;
cons.weighty = 0;
add(label_2, cons);

For more information: http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html 有关更多信息: http : //docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

Check this code, maybe it helps you: 检查此代码,也许可以帮助您:

public class GUITest {
private JPanel mainPanel;   
private JLabel l1;
private JLabel l2;
private JLabel l3;
private JButton b1;
private JButton b2;
private JTextField text;
private JFrame guiFrame;
private Container pane;

public GUITest() {
    // TODO Auto-generated constructor stub
    guiFrame = new JFrame();
    pane = new Container();
    pane.setLayout(new BorderLayout());
    //make sure the program exits when the frame closes
    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    guiFrame.setTitle("Example GUI");
    guiFrame.setSize(300,250);

    mainPanel = new JPanel(new GridBagLayout());

    l1 = new JLabel("Label 1");
    b1 = new JButton("Button 1");
    l2 = new JLabel("Label 2");
    b2 = new JButton("Button 2");
    l3 = new JLabel("Enter a sentence");
    text = new JTextField(50);

    GridBagConstraints c = new GridBagConstraints();
    c.gridheight = 1;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0;
    c.weighty = 0;
    Insets i = new Insets(5, 5, 5, 5);
    c.insets = i;

    c.gridx= 0;
    c.gridy = 0;
    mainPanel.add(l3,c);

    c.gridx = 1;
    c.gridy = 0;        
    mainPanel.add(text, c);

    c.gridx = 0;
    c.gridy = 1;
    mainPanel.add(b1,c);

    c.gridx = 1;
    c.gridy = 1;
    mainPanel.add(l1,c);

    c.gridx= 0;
    c.gridy = 2;
    mainPanel.add(b2,c);

    c.gridx = 1;
    c.gridy = 2;
    mainPanel.add(l2, c);



    pane.add(mainPanel,BorderLayout.NORTH);
    guiFrame.setContentPane(pane);
    guiFrame.setVisible(true);

}

public static void main(String[] args) {
    GUITest g = new GUITest();
}

} }

When using GridBagLayout, using relative positioning is always easier to maintain. 使用GridBagLayout时,始终相对易于维护。

Now regarding the left/right positioning, you need to properly use 现在关于左/右定位,您需要正确使用

  • weightx 重量x
  • anchor

Both properties will help you in there (there is another option using fill and playing with text alignment on JLabel, but it's a lot less elegant because your layout depends on both component properties and layout properties): 这两个属性都可以为您提供帮助(在JLabel上还有另一个使用填充和文本对齐方式的选择,但是它的优雅程度要差很多,因为您的布局取决于组件属性和布局属性):

And eventually the final outcome: 最终的最终结果是:

在此处输入图片说明

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

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;


public class TestGridBagLayout {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestGridBagLayout().initUI();
            }
        });
    }

    private JLabel label_1 =  new JLabel("Enter a sentence");
    private JLabel label_2 =  new JLabel("test");
    private JLabel label_3 =  new JLabel("test");
    private JLabel label_4 =  new JLabel("test");
    private JTextField textArea = new JTextField(15);
    private JButton button_1 = new JButton("button 1");
    private JButton button_2 = new JButton("button 2");
    private JButton button_3 = new JButton("button 3");

    protected void initUI() {
        JFrame frame= new JFrame(TestGridBagLayout.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new GridBagLayout());

        GridBagConstraints left = new GridBagConstraints();
        left.anchor = GridBagConstraints.EAST;
        left.weightx = 1;
        left.insets = new Insets(5, 5, 5, 5);
        GridBagConstraints right = new GridBagConstraints();
        right.weightx=1;
        right.gridwidth = GridBagConstraints.REMAINDER;
        right.anchor = GridBagConstraints.WEST;
        right.insets = new Insets(5, 5, 5, 5);

        panel.add(label_1, left);
        panel.add(textArea,right);

        panel.add(button_1 ,left);
        panel.add(label_2, right);

        panel.add(button_2,left);
        panel.add(label_3,right);

        panel.add(button_3,left);
        panel.add(label_4,right);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM