0

JLabelとJTextfieldをこのように配置しようとしています。

      First Name       Textbox        -> First Name is a label named as lblFirstname
      Last Name        Textbox        TextBox is JTextField

GridBagLayoutを使用してみました。

適用される制約は、

      lblFirstNameCons.gridx = 0;
      lblLastNameCons.gridy = 0;

      txtFirstName.gridx = 0;
      txtLastNameCons.gridy = 3;

私はこのような出力を得ています、

      First NameTextbox  -> There is no space and also, the JTextField is almost invisible.  
4

2 に答える 2

2

レイアウトはこのようなものにする必要があります。括弧内の値は、gridx と gridy (grix、gridy) です。

First Name (0, 0)       Textbox (1, 0)
Last Name  (0, 1)       Textbox (1, 1)
于 2012-09-14T07:37:46.927 に答える
1
  1. You should make sure that the fill property of the GridBagConstraint is set to HORIZONTAL for the textfield and make sure that the weightx is set to something greater than 0
  2. Or you can indicate to the textfield the desired number of columns to display (this will eventually influence the preferred size of the textfield).

Here is an example showing that:

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

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

public class TestGridBagLayout {

    protected void initUI() throws MalformedURLException {
        final JFrame frame = new JFrame();
        frame.setTitle(TestGridBagLayout.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JPanel panel = new JPanel(new GridBagLayout());
        JLabel firstName = new JLabel("First name:");
        JLabel lastName = new JLabel("Last name:");
        JTextField firstNameTF = new JTextField();
        JTextField lastNameTF = new JTextField();
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(3, 3, 3, 3);
        gbc.weightx = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(firstName, gbc);
        gbc.weightx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        panel.add(firstNameTF, gbc);
        gbc.gridwidth = 1;
        gbc.weightx = 0;
        panel.add(lastName, gbc);
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.weightx = 1;
        panel.add(lastNameTF, gbc);
        frame.add(panel);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }

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

}
于 2012-09-14T08:30:55.007 に答える