Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting JPanel layout

(Say) I've created a JPanel with three buttons. I want to place the buttons as follows (I've done this using netbeans GUI editor. But I need to write the whole GUI manually).

enter image description here

Can some one show me a way to achieve this.

(In words, I need to place some buttons right aligned, some other left aligned.)

like image 526
Anubis Avatar asked Dec 16 '22 21:12

Anubis


1 Answers

I guess you want the Configure button to be as far to the left as possible, and the ok and cancel grouped together to the right. If so, I would suggest using a BorderLayout and place the Configure button in WEST, and a flow-layout for Ok, Cancel and place that panel in the EAST.

Another option would be to use GridBagLayout and make use of the GridBagConstrant.anchor attribute.

Since you're taking the time to avoid the NetBeans GUI editor, here's a nice example for you :-)

enter image description here

Code below:

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

public class FrameTestBase {

    public static void main(String args[]) {

        // Will be left-aligned.
        JPanel configurePanel = new JPanel();
        configurePanel.add(new JButton("Configure"));

        // Will be right-aligned.
        JPanel okCancelPanel = new JPanel();
        okCancelPanel.add(new JButton("Ok"));
        okCancelPanel.add(new JButton("Cancel"));

        // The full panel.
        JPanel buttonPanel = new JPanel(new BorderLayout());
        buttonPanel.add(configurePanel, BorderLayout.WEST);
        buttonPanel.add(okCancelPanel,  BorderLayout.EAST);

        // Show it.
        JFrame t = new JFrame("Button Layout Demo");
        t.setContentPane(buttonPanel);
        t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        t.setSize(400, 65);
        t.setVisible(true);
    }
}
like image 88
aioobe Avatar answered Jan 11 '23 22:01

aioobe