Java 将页面右上角的组件与GridBagLayout Manager对齐

Java 将页面右上角的组件与GridBagLayout Manager对齐,java,swing,layout,jpanel,gridbaglayout,Java,Swing,Layout,Jpanel,Gridbaglayout,我试图创建一个类似facebook的登录页面,但我编写的代码并没有显示在页面的左上方,而是显示在页面的中心,我使用GridBagLayout和anchore在第一行设置文本 final JFrame f2=new JFrame("Admin Main"); f2.setSize(1350,730); f2.setVisible(true); f1.setVisible(fals

我试图创建一个类似facebook的登录页面,但我编写的代码并没有显示在页面的左上方,而是显示在页面的中心,我使用GridBagLayout和anchore在第一行设置文本

final JFrame f2=new JFrame("Admin Main");
                    f2.setSize(1350,730);
                    f2.setVisible(true);
                    f1.setVisible(false);
                    f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);![enter image description here][2]
                    GridBagLayout gbl=new GridBagLayout();
                    final JPanel p2=new JPanel(gbl){
        private Image img = ImageIO.read(new File("F:\\Untitled Folder\\Rohan\\football2.jpg"));
        @Override
                          protected void paintComponent( Graphics g ) { 
              super.paintComponent(g);

              g.drawImage(img, 0,0,1366,730, null);
              }
       };;
                    GridBagConstraints g2=new GridBagConstraints();
                    g2.insets=new Insets(3,3,3,3);
                    JLabel l2=new JLabel("Admin ID",JLabel.LEFT);
                    JLabel l3=new JLabel("Password",JLabel.LEFT);
                    l2.setFont(new Font("TimesRoman",Font.BOLD,16));
                    l2.setForeground(Color.BLUE);
                    l2.setBackground(Color.WHITE);
                    l3.setFont(new Font("TimesRoman",Font.BOLD,16));
                    l3.setForeground(Color.BLUE);
                    l3.setBackground(Color.WHITE);
                    final JTextField t1=new JTextField(15);
                    final JPasswordField pw1=new JPasswordField(15);
                    JButton b3=new JButton("Back");
                    JButton b4=new JButton("Sign in");
                    f2.add(p2);
                    g2.anchor=GridBagConstraints.FIRST_LINE_END;
                    g2.gridx=1;
                    g2.gridy=1;
                    p2.add(l2,g2);
                    g2.gridx=2;
                    g2.gridy=1;
                    p2.add(t1,g2);
                    g2.gridx=1;
                    g2.gridy=2;
                    p2.add(l3,g2);
                    g2.gridx=2;
                    g2.gridy=2;
                    p2.add(pw1,g2);
                    g2.gridx=1;
                    g2.gridy=3;
                    p2.add(b3,g2);
                    g2.gridx=2;
                    g2.gridy=3;
                    p2.add(b4,g2);

如果您希望它明确位于左上角,我宁愿使用西北锚。从左向右流动的文本的第一行结尾也会将文本放在右角,而从右向左流动的文本则相反

另外,将gridx和gridy切换为从0开始,而不是从1开始。并根据需要从中递增

例如:

g2.anchor=GridBagConstraints.NORTHWEST;
g2.gridx=0;
g2.gridy=0;
p2.add(l2,g2);
g2.gridx=1;
g2.gridy=0;
p2.add(t1,g2);
/*And so on for the rest of the block*/

使用第一条线作为锚定值

g2.anchor=GridBagConstraints.FIRST_LINE_START;

我发现您当前的布局存在两个问题:

  • 您将登录面板放在父级
    边框布局的中心(这样您的面板就会拉伸到其容器的大小)
  • GridBagLayout
    中没有任何东西会将组件“推”到顶部和左侧
  • 这里有几个选项:

  • 将登录面板嵌套到多个面板中(例如,使用BorderLayout,一次使用约束北,第二次使用约束西)
  • 将loginPanel添加到西部,然后在
    GridBagLayout
    的底部添加一个“填充”组件,以便将其他组件推到顶部
  • 下面是第二个解决方案的演示:

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import javax.swing.Box;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    
    public class TestLoginGridBagLayout {
    
        protected void initUI() throws MalformedURLException {
            JFrame frame = new JFrame("Admin Main");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JLabel background = new JLabel(new ImageIcon(new URL(
                    "http://media1.santabanta.com/full1/Football/Football%20Abstract/football-abstract-6a.jpg"))) {
                @Override
                public Dimension getPreferredSize() {
                    Dimension preferredSize = super.getPreferredSize();
                    Dimension layoutPreferredSize = super.preferredSize();
                    preferredSize.width = Math.max(preferredSize.width, layoutPreferredSize.width);
                    preferredSize.height = Math.max(preferredSize.height, layoutPreferredSize.height);
                    return preferredSize;
                }
            };
            background.setLayout(new BorderLayout());
            frame.add(background);
            GridBagLayout gbl = new GridBagLayout();
            final JPanel loginPanel = new JPanel(gbl);
            loginPanel.setOpaque(false);
            background.add(loginPanel, BorderLayout.WEST);
            JLabel adminIDLabel = new JLabel("Admin ID", JLabel.LEFT);
            JLabel passwordLabel = new JLabel("Password", JLabel.LEFT);
            adminIDLabel.setFont(new Font("TimesRoman", Font.BOLD, 16));
            adminIDLabel.setForeground(Color.BLUE);
            adminIDLabel.setBackground(Color.WHITE);
            passwordLabel.setFont(new Font("TimesRoman", Font.BOLD, 16));
            passwordLabel.setForeground(Color.BLUE);
            passwordLabel.setBackground(Color.WHITE);
            final JTextField adminID = new JTextField(15);
            final JPasswordField password = new JPasswordField(15);
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
            buttonPanel.setOpaque(false);
            JButton back = new JButton("Back");
            JButton signIn = new JButton("Sign in");
            buttonPanel.add(back);
            buttonPanel.add(signIn);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(3, 3, 3, 3);
            gbc.anchor = GridBagConstraints.FIRST_LINE_END;
            loginPanel.add(adminIDLabel, gbc);
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            loginPanel.add(adminID, gbc);
            gbc.gridwidth = 1;
            loginPanel.add(passwordLabel, gbc);
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            loginPanel.add(password, gbc);
            loginPanel.add(buttonPanel, gbc);
            GridBagConstraints gbcFiller = new GridBagConstraints();
            gbcFiller.weightx = 1.0;
            gbcFiller.weighty = 1.0;
            gbcFiller.fill = GridBagConstraints.BOTH;
            loginPanel.add(Box.createGlue(), gbcFiller);
            frame.pack();
            frame.setVisible(true);
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        new TestLoginGridBagLayout().initUI();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
    }
    
    我还冒昧地说:

    • 将变量重命名为有意义的名称(这使您的代码更易于他人阅读)
    • 将自定义背景图像面板替换为
      JLabel
    • 使用另一个
      LayoutManager
    • 再拍一张背景图片,因为我没有你的

    请单击gridbaglayout标签,然后按最新版本订购,我确信第一、第二页包含类似的代码,并且在表单中使用
    gridx/gridy
    实际上是不推荐的。使用
    gridwidth/gridheight
    是一种更好的方法(使用绝对值(1,2,3,…)或相对值(例如
    GridBagConstraints.rements
    ).无论如何,将主播设置为
    NORTHWEST
    不会解决这里的问题。没有效果,先生,它仍然在屏幕中间。.我正在使用Netbeans,我不认为这是因为。@GuillaumePolet不确定使用gridwith和gridheight而不是gridx和gridy来实现什么,因为它们做的事情不同。每个c这里的组件总是一个。因此,我不认为使用Widt和height属性可以解决任何问题,除了组件将占用多少空间。@trappski查看我的答案了解更多信息。使用绝对值作为
    gridx/gridy
    很快就成了一个要维护的噩梦。假设您有一个4乘4的网格,并且您决定将其设置为5乘45并引入一个新的中心行和一个新的中心列。您必须更改所有约束。在
    gridwith=rements
    gridwidth=1
    之间切换允许您“播放”对于网格的行。网格高度和网格的列也是如此。在所有情况下,您的代码都不能解决这个问题。谢谢,实际上添加了Box.createGlue()和weighty=1就可以了