GridBagLayout组件未对齐

时间:2018-10-08 00:11:10

标签: java swing layout-manager gridbaglayout

我最近一直在与布局管理器GridBagLayout合作,并且在使用它的网格系统时遇到了麻烦。

我想做的就是在这里创建我创建的JButton:

    JButton myButton = new JButton("Some text");

    gc.gridx = 2;
    gc.gridy = 4;
    gc.weightx = 0.5;
    gc.weighty = 0.5;

    jp.add(myButton, gc);

在给定代码的情况下,要超过2列,而要向下4行:

gc.gridx = 2 gc.gridy = 4

我在此处定义组件(JPanel)中的列数和行数:

GridBagConstraints gc = new GridBagConstraints();
    gc.gridwidth = 2;
    gc.gridheight = 10;

但是,我得到的是:

enter image description here

尽管这些组件位于明显不同的部分中,但它们是重叠的。任何帮助深表感谢。这是完整的代码:

package com.UI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
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 UserInterface{

public static void main(String[] args) {


    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {

            JFrame f = createFrame();

            JPanel jp = createPanel();

            addLabelAndText(jp);

            f.add(jp, BorderLayout.WEST);

        }

    });



}



static JFrame createFrame() {
    JFrame f = new JFrame();

    f.setLayout(new BorderLayout());


    f.setSize(new Dimension(600, 600));
    f.setVisible(true);

    f.setLocationRelativeTo(null);

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    return f;
}


static JPanel createPanel() {

    JPanel jp = new JPanel();

    jp.setBackground(Color.gray);

    jp.setLayout(new GridBagLayout());


    Dimension size = jp.getPreferredSize();
    size.width = 200;

    jp.setPreferredSize(size);

    jp.setBorder(BorderFactory.createEtchedBorder());


    return jp;

}

static void addLabelAndText(JPanel jp) {//How to call a type represented by the passed String? JLabel, for example?

    GridBagConstraints gc = new GridBagConstraints();
    gc.gridwidth = 2;
    gc.gridheight = 10;

    JTextField jtb = new JTextField(5);

    JLabel jl = new JLabel("Enter input here: ");


    gc.gridx = 2;
    gc.gridy = 0;
    gc.weightx = 0.5;
    gc.weighty = 0.5;

    gc.anchor = GridBagConstraints.NORTHEAST;


    jp.add(jtb, gc);

    gc.gridx = 1;
    gc.gridy = 2;
    gc.weightx = 0.5;
    gc.weighty = 0.5;

    gc.anchor = GridBagConstraints.NORTHWEST;
    gc.anchor = GridBagConstraints.FIRST_LINE_END;

    jp.add(jl, gc);

    JButton myButton = new JButton("Some text");

    gc.gridx = 2;
    gc.gridy = 4;
    gc.weightx = 0.5;
    gc.weighty = 0.5;

    jp.add(myButton, gc);


  }


}

感谢您的帮助

0 个答案:

没有答案