JPanel layout setup

(Say) I created a JPanel with three buttons. I want to put the buttons as follows (I did this using the netbeans graphical editor, but I need to write the entire GUI manually).

enter image description here

Can anyone show me a way to achieve this.

(In words, I need to put some buttons to the right, some others are left-aligned.)

+5
source share
1 answer

I think you want the Configure button to be as far left as possible, and ok and cancel are grouped together to the right. If so, I would suggest using BorderLayoutand placing the Configure button in WEST and the layout for Ok, Cancel and placing this panel in EAST.

- GridBagLayout GridBagConstrant.anchor.

, NetBeans, : -)

enter image description here

:

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);
    }
}
+11

All Articles