java - 使用 GridBagLayout 设置坐标

标签 java swing gridbaglayout

我对坐标 x 和 y 有疑问。我使用 GridBagLayout gridx=0,gridy=0,但所有组件都完全居中对齐。我需要设置左上对齐 0,0 但我使用 GridBagLayout 的解决方案不起作用。

现在我展示代码和图片。需要左对齐。默认居中对齐,但需要为组件设置左上角对齐,因为我需要在 JFrame 底部绘制两张图片。

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class Zobrazenie extends JPanel {
private static final long serialVersionUID = 1L;
    JButton b1,b2,b3,b4,b5;
    GridBagConstraints gbc = new GridBagConstraints();
    Zobrazenie()
    {
        setLayout(new GridBagLayout());
        gbc.insets=new Insets(10,10,10,10);

        gbc.gridx=0;
        gbc.gridy=0;
        gbc.anchor=GridBagConstraints.WEST;
        b1=new JButton("Button 1");
        add(b1,gbc);

        gbc.gridx=0;
        gbc.gridy=1;
        b2=new JButton("Button 2");
        add(b2,gbc);

        gbc.gridx=0;
        gbc.gridy=2;
        b3=new JButton("Button 3");
        add(b3,gbc);

        gbc.gridx=0;
        gbc.gridy=3;
        b4=new JButton("Button 4");
        add(b4,gbc);

        gbc.gridx=0;
        gbc.gridy=4;
        b5=new JButton("Button 5");
        add(b5,gbc);
    }
public static void main(String[] args)
{
    JFrame jf = new JFrame();
    Zobrazenie zb = new Zobrazenie();
    jf.setSize(400,300);
    jf.setTitle("Okno");
    jf.setLocationRelativeTo(null);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.add(zb);
    jf.setVisible(true);
}
}

还有图片:http://img14.imageshack.us/img14/7243/oknouw.jpg

最佳答案

anchorfill 仅在您指定 weighx 和/或 weighty 的值大于 0 时才起作用.

现在的问题是您希望如何分配额外的空间。

关于java - 使用 GridBagLayout 设置坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14463731/

相关文章:

java - JButton 用颜色创建

Java - 尝试一次绘制多个形状,有些形状丢失

Java GridBagLayout 不工作

java - GridBagLayout & JScrollPane : how to reduce row height?

java - 获取 GridBagLayout 单元格的像素尺寸

java - 如何使用 Selenium (Java) 滚动溢出 div?

java - Git 存储库到 Gradle 依赖项

java - 为什么说SessionFactory是ConnectionProvider的客户端

java - 动态添加 JPanel 时 JScrollPane 自动向下滚动

java - 当 JasperViewer 出现并且我关闭它时,主框架/父框架也关闭了