java - gridbaglayout 将组件定位到中心

标签 java swing position gridbaglayout

我正在使用 GridBagLayout 作为面板,我有一个名为 show_date_info 的标签,我想将其放置在第 3 行的中间(gridy=2),但它出现在最左侧。或者我必须通过设置 label 的 gridx 来实现这一点。谢谢。

    setLayout(new GridBagLayout());

    c.anchor = GridBagConstraints.NORTHEAST;
    c.weighty = 0;
    c.weightx = 1;
    c.insets = new Insets(10,0,0,0);  
    c.gridx = 5;      
    c.gridy = 0;   
    c.gridwidth = 1;        
    add(Logoutbtn, c);

    c = new GridBagConstraints();
    c.weighty = 1;
    c.weightx = 0.1;
    c.insets = new Insets(80,180,0,0);  
    c.gridx = 1;   
    c.gridy = 1;        
    c.gridwidth = 1;        
    add(startdatelabel, c);

    c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weighty = 1;
    c.weightx = 1;
    c.insets = new Insets(80,0,0,80);  
    c.gridx = 2;   
    c.gridy = 1;        
    c.gridwidth = 1;        
    add(picker1, c);

    c = new GridBagConstraints();
    c.weighty = 1;
    c.weightx = 0.1;
    c.insets = new Insets(80,80,0,0);  
    c.gridx = 4;   
    c.gridy = 1;        
    c.gridwidth = 1;        
    add(enddatelabel, c);

    c.fill = GridBagConstraints.HORIZONTAL;
    c.weighty = 1;
    c.weightx = 1;
    c.insets = new Insets(80,0,0,180);  
    c.gridx = 5;   
    c.gridy = 1;        
    c.gridwidth = 1;        
    add(picker2, c);

    c = new GridBagConstraints();
    c.anchor = GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.REMAINDER;
    c.insets = new Insets(-80,0,0,0);   
    c.gridy = 2;        
    //c.gridwidth = 1;        
    add(show_date_info, c);

    c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weighty = 1;
    c.weightx = 1;
    c.insets = new Insets(0,20,0,20);  
    c.gridx = 0;   
    c.gridy = 3;        
    c.gridwidth = 7;         
    add(sp,c);

    c.fill = GridBagConstraints.NONE;
    c.insets = new Insets(-100,10,0,10);  
    c.gridx = 5;   
    c.gridy = 4;        
    c.gridwidth = 1;         
    add(confirmbtn,c);

最佳答案

无需创建不同的GridBagConstraints对象。只需创建单个对象并使用它即可。

确保

c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1; // 100%
c.gridy = 2 // 3rd row
c.gridwidth = max_number_of_columns;

使用JLabel(text,horizontalAlignement)

例如

new JLabel("In center",SwingConstants.CENTER) // to keep label in center

关于java - gridbaglayout 将组件定位到中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25338509/

相关文章:

java - XML 验证中的问题。 MIn 出现工作不正常

java - 使用paint(Graphics p)时删除java中的一行?

java - 向 JTable 添加多行

java - Action 事件的计数器变量

javascript - 滞后于 onmousemove 和 div 位置

html - 正确定位元素

r - ggplot2:如何微调 geom_beeswarm 中点的位置?

java - 堆内存每次都触及新高

java - 将 GuiceServletContextListener 连接到现有的注入(inject)器

java - 从外部更改和更新 JPanel 组件,JFrame 不起作用,Swing