简体   繁体   English

Java Swing中的垂直对齐

[英]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. 我在创建3个面板并将其添加到主面板时尝试了此代码。 It shows two buttons on north and one button on south! 它在北显示两个按钮,在南显示一个按钮! Can someone help me? 有人能帮我吗?

Note, the default layout of JPanel is FlowLayout ; 注意, JPanel的默认布局是FlowLayout a GridBagLayout with default constraints is centered in the frame's BorderLayout.CENTER . 具有默认约束的GridBagLayout位于框架的BorderLayout.CENTER Also, pack() the enclosing Window and display it last. 同样, pack()封闭的Window并最后显示它。 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);

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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