Align JPanel button

0

I want to align a single button to JPanel, but I'm not getting it, it's using the default layout.

public class Test extends JFrame {

    private JButton btn;
    private JPanel painel;
    private JScrollPane scroll;
    private JTextArea tArea;

    public Test() {

        btn = new JButton("Sair");
        btn.setPreferredSize(new Dimension(72, 35));
        btn.addActionListener(e -> System.exit(0));

        painel = new JPanel();
        painel.add(btn, FlowLayout.LEFT); //nao funciona

        JScrollPane scroll = new JScrollPane(tArea = new JTextArea());
        scroll.setPreferredSize(new Dimension(400, 300));
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        Container cp = getContentPane();
        cp.add(painel, "North");
        cp.add(scroll, "Center");

        getRootPane().setDefaultButton(btn);

        setSize(400, 280);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new Test().setVisible(true);
    }

}
    
asked by anonymous 21.05.2017 / 00:51

1 answer

1

Does not work because in the case of FlowLayout , it is fine in this way that you configure the alignment mode of it, it is not like with BorderLayout .

You should retrieve the layout of the JPanel and call the setAlignment() , passing one of the five modes supported by this layout manager, in your case, the FlowLayout.LEFT :

painel = new JPanel();
FlowLayout layout = (FlowLayout) painel.getLayout();
layout.setAlignment(FlowLayout.LEFT);
painel.add(btn);

Or simplifying:

((FlowLayout)painel.getLayout()).setAlignment(FlowLayout.LEFT);

There is another way too, which is instantiating this layout at the start of the panel, already passing the alignment, although it seems a waste, because this layout is already created by java, but may be an option:

painel = new JPanel(new FlowLayout(FlowLayout.LEFT));

Here are some very useful links:

21.05.2017 / 01:09