setPreferredSize and setSize do not work

Asked

Viewed 1,226 times

1

I used the setPreferredSize and the setSize on the button color1 but no effect on 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);
}

1 answer

1


By default, Jframe uses Borderlayout, which means that when you add a Jbutton, as this is the only component in the frame, it will be resized to fill the entire window. You can consult this example to get a better sense of what’s going on with your layout.

If you want the size of the button to be exactly the one you set with Setpreferredsize() then you should change the layout of Jframe to something different: Flowlayout or Gridlayout, for example. After this 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);
    }

}

Browser other questions tagged

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