setPreferredSize and setSize do not work

1

I've used setPreferredSize and setSize on the color1 button but no effect in the application, it continues using the entire application.

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));

    //PAINEIS
    JPanel fundo = new JPanel();

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

    //BOTOES
    JButton color1 = new JButton();

    color1.setPreferredSize(new Dimension(WIDTHBUTTON, HEIGHTBUTTON));
    color1.setBackground(RED);

    //ADICIONAR NO FRAME
    janela.add(fundo);
    janela.add(color1);
}
    
asked by anonymous 18.07.2015 / 07:51

1 answer

1

By default, JFrame uses the BorderLayout Layout, which means that when you add a JButton, as this is the only component in the frame, it will be resized so that it fills the entire window. You can check out this example to get a better insight into what's happening with your layout.

If you want the button size to be exactly what you define with SetPreferredSize () then you should change the JFrame layout to something else: FlowLayout or GridLayout, for example. After that you can set the size with SetPreferredSize ().

In your example the code would look like this:

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

public class JanelaPrincipal {

    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()
            {
                JanelaPrincipal j = new JanelaPrincipal();
                j.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(new FlowLayout()); //altera o layout para FlowLayout explicitamente

        color1.setPreferredSize(new Dimension(100,50));//dimensoes do botão

        c.add(color1);
    }

}
    
18.07.2015 / 15:45