Domanda

I am having trouble with GridBagLayout.

A user selects a file, and if that file is bigger than the JTextArea that I display it in, all the Swing components in the shared GridBagLayout go haywire. If it is able to fit in the JTextField, all the Swing components are fine.

Here is a screenshot of the JFrame layout I desire:

Want

And here is the JFrame layout I get when the JTextArea containing the file path is bigger than its allotted size.

Have

All the other JTextFields are affected as well as the buttons below. I don't care if the text in the JTextArea is bigger than its size, I just want all the swing components to stay the same.

Here is the code where I add the Swing components into the File info panel:

    //Setup layout.
    gbc = new GridBagConstraints();
    //File info panel.
    gbc.insets = new Insets(3, 10, 3, 10);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    info_panel.add(first_name_jta, gbc);
    gbc.gridx = 1;
    gbc.gridy = 0;
    info_panel.add(first_name_tf, gbc);
    gbc.gridx = 0;
    gbc.gridy = 1;
    info_panel.add(last_name_jta, gbc);
    gbc.gridx = 1;
    gbc.gridy = 1;
    info_panel.add(last_name_tf, gbc);
    gbc.gridx = 0;
    gbc.gridy = 2;
    info_panel.add(frame_type_jta, gbc);
    gbc.gridx = 1;
    gbc.gridy = 2;
    info_panel.add(frame_type_cb, gbc);
    gbc.gridx = 0;
    gbc.gridy = 3;
    info_panel.add(eye_size_jta, gbc);
    gbc.gridx = 1;
    gbc.gridy = 3;
    info_panel.add(eye_size_tf, gbc);

    //Frame panel.
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 2;
    gbc.fill = GridBagConstraints.BOTH;
    frame_panel.add(file_path_tf, gbc);
    gbc.gridy = 1;
    frame_panel.add(info_panel, gbc);
    gbc.gridy = 2;
    gbc.insets = new Insets(10, 60, 10, 60);
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    frame_panel.add(save_button, gbc);
    gbc.gridx = 1;
    gbc.gridy = 2;
    gbc.anchor = GridBagConstraints.EAST;
    frame_panel.add(cancel_button, gbc);

Any ideas?

È stato utile?

Soluzione

Okay, that took a bit of effort.

Basically, when you build the frame_panel, you use gridwidth = 2 for the file_path_tf and info_panel, which is all fine an good, but you never reset the attribute when you add the buttons.

This means that save_button can occupy columns 0 and 1 and cancel_button can occupy 1 and 2

Reset the gridwidth attribute after you've added the info_pane and before you add the buttons

gbc.gridwidth = 1;

Also, I think you'll find JLabels much easier to deal with then JTextAreas for labeling fields, but that's just me.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top