简体   繁体   中英

Vertical alignement in Java Swing

How can I make buttons like this?

在此处输入图片说明

        JPanel jp = new JPanel();
        JPanel jpB1 = new JPanel();
        JPanel jpB2 = new JPanel();
        JPanel jpB3 = new JPanel();
        JButton jb1 = new JButton("button1");
        JButton jb2 = new JButton("button2");
        JButton jb3 = new JButton("button3");
            ...
        JLabel jl = new JLabel("label");
        ...
        jp.setLayout(new BorderLayout());
        ...
        jpB1.add(jb1);
        jpB2.add(jb2);
        jpB3.add(jb3);
        ...
        jp.add(jpB1, BorderLayout.NORTH);
        jp.add(jpB2, BorderLayout.CENTER);
        jp.add(jpB3, BorderLayout.SOUTH);
            ...

I tried this code on creating 3 panels and add them to the main panel. It shows two buttons on north and one button on south! Can someone help me?

Note, the default layout of JPanel is FlowLayout ; a GridBagLayout with default constraints is centered in the frame's BorderLayout.CENTER . Also, pack() the enclosing Window and display it last. Using Initial Threads left as an exercise.

Addendum: A useful trick for solving layout problems is setting the background color of an enclosing container to a contrasting color, for example

jpB2.setBackground(Color.blue);

图片

import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Bouton2 {

    public static void main(String[] args) {

        final int LARGEUR = 400;
        final int HAUTEUR = 300;

        JFrame jf = new JFrame();
        JPanel jp = new JPanel();
        JPanel jpB1 = new JPanel();
        JPanel jpB2 = new JPanel(new GridBagLayout());
        JPanel jpB3 = new JPanel();
        JButton jb1 = new JButton("Cliquez ici");
        JButton jb2 = new JButton("Je compte");
        JButton jb3 = new JButton("J'agrandis");

        JLabel jl = new JLabel("0 clic");

        jp.setLayout(new BorderLayout());

        jpB1.add(jb1);
        jpB2.add(jb2);
        jpB3.add(jb3);

        jp.add(jpB1, BorderLayout.NORTH);
        jp.add(jpB2, BorderLayout.CENTER);
        jp.add(jpB3, BorderLayout.SOUTH);

        jf.setTitle("Fenêtre Bouton2");
        jf.setContentPane(jp);
        jf.pack();
        jf.setSize(LARGEUR, HAUTEUR);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setLocationRelativeTo(null);
        jf.setVisible(true);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM