Align JPANEL button

Asked

Viewed 623 times

0

I want to align a single button to the Jpanel, but I’m not succeeding, 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);
    }

}
  • Line up like, left?

  • That’s right, I forgot to say.

  • Did the answer help you? If yes, you can mark it as accepted by clicking on v the left of the answer :)

1 answer

1

It doesn’t work because in the case of FlowLayout, not quite in this way you configure its alignment mode, it’s not how you do with the BorderLayout.

You must recover the layout of the Jpanel and call the method setAlignment(), passing one of the five modes supported by this layout manager, in your case the mode FlowLayout.LEFT:

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

Or by simplifying:

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

There is another way too, that is instantiating this layout at the startup of the panel, already passing the alignment, despite finding a waste, because this layout is already created by java, but can be an option:

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

I leave here some very useful links about:

Browser other questions tagged

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