How to center a component using null layout?

Asked

Viewed 525 times

1

my knob I want to center is 100 pixels wide. Jframe is 350 wide. how to center?

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ComboBoxLUL;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author Igor
 */
public class PainelPrincipal extends JPanel {

    private JComboBox jcbGenero;

    private JComboBox jcbCasado;

    private JButton btnSalva;

    private JLabel lblNome;

    private JLabel lblIdade;

    private JLabel lblCpf;

    private JTextField txtCpf;

    private JTextField txtNome;

    private JTextField txtIdade;

    private final String[] genero = {"Masculino ", "Feminino"};

    private final String[] estCivil = {"Casado", "Solteiro"};

    // private Integer[] genero = {1,2,3};// essa forma funciona. int nao. mas o resultado é o msm.

    PainelPrincipal() {
        this.setLayout(null);

        txtNome = new JTextField();
        txtNome.setBounds(45, 90, 120, 25);
        this.add(txtNome);
        ///////////
        txtCpf = new JTextField();
        txtCpf.setBounds(45, 50, 120, 25);
        this.add(txtCpf);
        ///////////
        txtIdade = new JTextField();
        txtIdade.setBounds(45, 130, 120, 25);
        this.add(txtIdade);

        //////////
        lblCpf = new JLabel("CPF");
        lblCpf.setBounds(10, 50, 120, 25);
        this.add(lblCpf);
        //////////

        lblIdade = new JLabel("Idade");
        lblIdade.setBounds(10,90,120,25);
        this.add(lblIdade);

        lblNome = new JLabel("Nome");
        lblNome.setBounds(10, 130, 120, 25);
        this.add(lblNome);

        jcbGenero = new JComboBox(genero);
        jcbGenero.setBounds(170, 50, 120, 25);
        this.add(jcbGenero);

        jcbCasado = new JComboBox(estCivil);
        jcbCasado.setBounds(170, 90, 120, 25);
        this.add(jcbCasado);

        btnSalva = new JButton("Salvar");
        btnSalva.setBounds(175, 175, 100, 25);
        this.add(btnSalva);

        btnSalva.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
              //@@@@@@@@@@@@@@@@@@@@@@
            }

        });
        this.add(btnSalva);

    }

}

1 answer

3


Just use a little math: if the screen is 350px full width and the component is 100, for it to occupy a central portion, its horizontal position on the screen is:

(outflow/2) - (outflow/2)

Applying this calculation with the informed data results:

350/2 - 100/2 = 125

This 125 is the horizontal position from where your button should be positioned on setBounds. Behold:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.*;

/**
 *
 * @author Igor
 */
public class PainelPrincipal extends JPanel {

    private JComboBox jcbGenero;

    private JComboBox jcbCasado;

    private JButton btnSalva;

    private JLabel lblNome;

    private JLabel lblIdade;

    private JLabel lblCpf;

    private JTextField txtCpf;

    private JTextField txtNome;

    private JTextField txtIdade;

    private final String[] genero = {"Masculino ", "Feminino"};

    private final String[] estCivil = {"Casado", "Solteiro"};

    // private Integer[] genero = {1,2,3};// essa forma funciona. int nao. mas o resultado é o msm.
    PainelPrincipal() {
        this.setLayout(null);

        txtNome = new JTextField();
        txtNome.setBounds(45, 90, 120, 25);
        this.add(txtNome);
        ///////////
        txtCpf = new JTextField();
        txtCpf.setBounds(45, 50, 120, 25);
        this.add(txtCpf);
        ///////////
        txtIdade = new JTextField();
        txtIdade.setBounds(45, 130, 120, 25);
        this.add(txtIdade);

        //////////
        lblCpf = new JLabel("CPF");
        lblCpf.setBounds(10, 50, 120, 25);
        this.add(lblCpf);
        //////////

        lblIdade = new JLabel("Idade");
        lblIdade.setBounds(10, 90, 120, 25);
        this.add(lblIdade);

        lblNome = new JLabel("Nome");
        lblNome.setBounds(10, 130, 120, 25);
        this.add(lblNome);

        jcbGenero = new JComboBox(genero);
        jcbGenero.setBounds(170, 50, 120, 25);
        this.add(jcbGenero);

        jcbCasado = new JComboBox(estCivil);
        jcbCasado.setBounds(170, 90, 120, 25);
        this.add(jcbCasado);

        btnSalva = new JButton("Salvar");
        // btnSalva.setPreferredSize(new Dimension(100, 25));
        // JPanel btnPan = new JPanel(new FlowLayout(FlowLayout.CENTER));
        // btnPan.add(btnSalva);
        // this.add(btnPan);
        btnSalva.setBounds(125, 175, 100, 25);
        this.add(btnSalva);

        btnSalva.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                //@@@@@@@@@@@@@@@@@@@@@@
            }

        });
        this.add(btnSalva);

    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame f = new JFrame();
                f.getContentPane().add(new PainelPrincipal(), BorderLayout.CENTER);
                f.setPreferredSize(new Dimension(350, 350));
                f.pack();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setVisible(true);
            }
        });
    }

}

But as a suggestion, avoid always using absolute layout. It makes it difficult to maintain the interface, because any future changes you will have to leave by repositioning all components manually, imagine a screen with dozens of these? Not to mention that depending on the resolution and size of the monitor, your interface may look different than you programmed. Read on Layoutmanager, there are several native and other very good community options, and the best is that you can merge all of them.

Here are some links about Layoutmanager:

  • 2

    avoid using absolute layout. +1

  • really it was mt easy. I went to sleep thinking and woke up with the answer. it’s half of the screen less half of the component xD

  • @Igoraugusto even so, from a researched on managers layouts, they are much more interesting, position in the hand component by component is cold my friend kkkkk

  • Yes. I’m a beginner. I was afraid of ready layouts. I always dreamed of doing everything on hand. but it takes a long time. I will search yes. which one you tell me? who has certain control as the setBounds method? dragging buttons on the netbenas almost led me to suicide. de mt problem kkkk

  • @Igoraugusto in the question link has the main java, usually they are enough, if you take how each works. This link explains a little of each: http://www.caelum.com.br/apostila-java-testes-xml-design-patterns/mais-swing-layout-managers-mais-componentes-e-details/

  • @Igoraugusto if the answer helped you solve, you can accept it by clicking on v the left, this way it will serve as reference for other people :)

Show 1 more comment

Browser other questions tagged

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