Spacing with Gridbaglayout

Asked

Viewed 460 times

3

I’m putting together a layout for testing with Gribbaglayout, but I’m having difficulties with the positioning of the elements. The frame has two panel. I want the items on the left panel (Label 1, text 1...) to have a small left spacing and Label 1 to have a small upper spacing as it is "stuck". My main question is as to Weight, because I imagine that it is with him that I put this but I could not. Below the photo and the code:

  import java.awt.BorderLayout;
  import java.awt.Color;
  import java.awt.Dimension;
  import java.awt.GridBagConstraints;
  import java.awt.GridBagLayout;
  import java.awt.GridLayout;
  import javax.swing.BorderFactory;
  import javax.swing.ImageIcon;
  import javax.swing.JButton;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.JPanel;
  import javax.swing.JTextField;
  import javax.swing.WindowConstants;

public class Teste{

private JButton btnCalc;
private JLabel origemText;
private JLabel destinoText;
private JPanel panel1, panel2;
private JLabel labelPanel2;
private JTextField texto1;
private JTextField texto2;

public Teste() {
    JFrame frame = new JFrame();
    frame.setTitle("teste");
    frame.setSize(1000, 500);
    frame.getContentPane().setLayout(new BorderLayout());


    origemText = new JLabel("Label 1");
    texto1 = new JTextField("Texto 1"); 
    destinoText = new JLabel("Label 2");
    texto2 = new JTextField("Texto 2");
    btnCalc = new JButton("Botão 1");

    GridBagConstraints cons = new GridBagConstraints();
    panel1 = new JPanel();
    panel1.setLayout(new GridBagLayout());
    panel1.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
    panel1.setPreferredSize(new Dimension(180, 200));

    cons.anchor = GridBagConstraints.NORTHWEST;
    cons.gridx = 0;
    cons.gridy = 0;
    cons.weighty = 0.1;
    panel1.add(origemText, cons);

    cons.gridx = 0;
    cons.gridy = 1;
    cons.weighty = 0.2;
    cons.weightx = 0.1;
    panel1.add(texto1, cons);

    cons.gridx = 0;
    cons.gridy = 2;
    cons.weighty = 0.1;

    panel1.add(destinoText, cons);

    cons.gridx = 0;
    cons.gridy = 3;
    cons.weighty = 0.6;
    panel1.add(texto2, cons);

    cons.gridx = 0;
    cons.gridy = 4;
    cons.weighty = 9.0;

    panel1.add(btnCalc, cons);

    panel2 = new JPanel();
    panel2.setLayout(new GridBagLayout());
    panel2.setSize(200, 300);

    labelPanel2 = new JLabel("Panel 2");

    panel2.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));

    panel2.add(labelPanel2);

    frame.getContentPane().add(BorderLayout.CENTER, panel2);
    frame.getContentPane().add(BorderLayout.WEST, panel1);


    frame.setVisible(true);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    new Teste();
}
}

EDIT

inserir a descrição da imagem aqui

1 answer

3


What you’re looking for is the Insets:

cons.insets = new Insets(20, 20, 0, 0);

Image example with Insets zeroed: Imagem sem Insets

The same image, only now using Insets: Imagem com Insets 15

The weight, contrary to what you thought, it serves to deal with the size of the elements, when the window is resized. The image on the left, then has the weight of 0.5 for each image. The one on the right is 0.4 the first, and 0.6 the second, making one more cropped than the other:

Imagem com weights equilibradosImagem com diferentes weights

Follow the code used if you want to test it:

import java.awt.*;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.io.*;
import java.net.*;
import java.awt.image.BufferedImage;

class TesteInsets extends JPanel {

    JLabel soLogo, soLogo2;
    BufferedImage img, img2;

    public TesteInsets() {

        setLayout(new GridBagLayout());

        try {

        URL url = new URL("http://i.imgur.com/xIUCtPo.png");
        URL url2 = new URL("http://i.imgur.com/kmNQziR.png");

        img = ImageIO.read(url);
        img2 = ImageIO.read(url2);

        } catch (IOException e) {
        }

        soLogo = new JLabel();
        soLogo2 = new JLabel();
        soLogo.setIcon(new ImageIcon(new ImageIcon(img).
          getImage().getScaledInstance(175, 175, Image.SCALE_SMOOTH)));
        soLogo2.setIcon(new ImageIcon(new ImageIcon(img2).
          getImage().getScaledInstance(175, 175, Image.SCALE_SMOOTH)));

        GridBagConstraints c = new GridBagConstraints();

         c.weightx = 0.6;
         c.gridx = 0;
         c.gridy = 0;
         c.insets = new Insets(15, 15, 15, 0);
         add(soLogo, c);

         c.weightx = 0.4;
         c.gridx = 1;
         c.gridy = 0;
         c.insets = new Insets(15, 15, 15, 15);
         add(soLogo2, c);

    }

    public static void criarInterface() {

    JFrame janela = new JFrame("Teste Insets");
    janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JComponent painelConteudo = new TesteInsets();

    painelConteudo.setOpaque(true);
    janela.setContentPane(painelConteudo);
    janela.setResizable(true);
    janela.pack();
    janela.setVisible(true);

    }

    public static void main(String[] Args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                criarInterface();
            }
        });
    }

}

Visit the Javadoc for more examples.

  • Worked out, buddy. I had already read this Weight function, but I was using it and I saw that it was kind of organizing the spacing, but really that’s what you said. Half frame is with setResizable(false), is it right to use Weight in my code? Or would not even need?

  • @Ablon Se is with setResizable(false), I see no reason to use the weight. Also, I suggest you do not set the size using frame.setSize() - the ideal is that you let the elements choose their sizes, and use the frame.pack() in the end.

  • Yes, but if I remove the Weight, although I can determine the distance between the elements with the insets, they are organized in the center of that Jpanel. I updated with print

  • @Ablon O weight does what you want, but he does it for the wrong reason. It’s important you imagine how your layout will be at the end. The idea of using the layout managers is usually to let the elements "position themselves" within them. If this field will have only these five elements and they need to stay at the top, I suggest you use another layout, like the BorderLayout and put them on North. But if you are eventually to fill the entire field, you need to add new elements so that they occupy their definitive positions.

  • 1

    @Ablon Remember you can put JPanel inside JPanel, with different layouts! A GridBagLayout within a BorderLayout may be what you seek (think better than "patch" with the weight).

  • @Ablon believes that your initial doubt has already been resolved, however as you develop you end up evolving your project and finding new doubts. I advise you to mark that answer as accepted and if you need to start another topic with your new question. However, take a look at this topic before to see if it helps you a little: Positioning of components using Gridbaglayout

  • Thanks to you!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.