How to set the Jbutton location to the size of a Panel

2

I would like to set the location of color1 to the size of a JPanel, in the same way I did with fundo

public static void janelaPrincipal()
{
    //FRAME
    JFrame janela = new JFrame();
    janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    janela.pack();
    janela.setResizable(false);
    janela.setVisible(true);
    janela.setSize(new Dimension(WIDTH, HEIGHT));   
    janela.setLocation((SCREEN.width / 2) - (WIDTH / 2), (SCREEN.height / 2) - (HEIGHT / 2));

    Container c = janela.getContentPane();
    c.setLayout(new FlowLayout());

    //PAINEIS
    JPanel fundo = new JPanel();

    fundo.setPreferredSize(new Dimension(WIDTH, HEIGHT));
    fundo.setBackground(background);

    //BOTOES
    JButton color1 = new JButton();
    JButton color2 = new JButton();

    color1.setPreferredSize(new Dimension(WIDTHBUTTON, HEIGHTBUTTON));
    color1.setLocation(HEIGHT / 2, WIDTH /2);
    color1.setBackground(RED);

    //ADICIONAR NO FRAME
    c.add(fundo);
    fundo.add(color1);

}

    
asked by anonymous 18.07.2015 / 18:59

1 answer

2

The main question should be: Why do you want to absolutely position your components?

Java interfaces can run on a large number of platforms, with different screen resolutions and using different PLAFs . For these reasons, absolute positioning of components is not the best practice. In order to build a robust GUI that looks the same regardless of the device settings where you are running, I would suggest using a layout manager, or several, in conjunction with padding and margins for whitespace to organize the components.

If you still want to manually control the placement of the button, simply remove the Layout from the component where you placed the button using the setLayout(null) method. After removing the layout you can use the same logic used for JPanel.

Here is a very simple example of what you can do to put the button at a specific position in the window:

import java.awt.*;
import javax.swing.*;

public class MainForm {

    protected JFrame  janela = new JFrame("Teste");
    protected JButton color1 = new JButton("Exemplo");

    public static void main(String st[]) {
        SwingUtilities.invokeLater( new Runnable()
        {
            public void run()
            {
                MainForm mf = new MainForm();
                mf.load();
            }
        });

    }
    public void load() {

    janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        janela.setSize(new Dimension(500, 500));   
        janela.setResizable(false);
    janela.setVisible(true);

    Container c = janela.getContentPane();
    c.setLayout(null); //vamos fazer a gestão manualmente
    color1.setBounds(250, 50, 150, 50); //dimensoes e posicionamento do botão (os dois primeiros valores indicam a posicao absoluta do botao)
    c.add(color1);
    }

}

I also suggest reading link

    
18.07.2015 / 19:49