如何在面板中动态添加按钮?

时间:2016-08-30 08:59:45

标签: java swing jpanel layout-manager gridbaglayout

我想在水平和垂直方向的面板中动态添加标签。我试过这段代码。

GridBagConstraints labelConstraints = new GridBagConstraints();

        // Add buttons
        for(int i = 0; i < indexer; i++)
        {
             // Label constraints
            labelConstraints.gridx = 1;
            labelConstraints.gridy = i;

            // Add them to panel                
            panel.add(listOfLabels.get(i), labelConstraints);
        }

        // Align components top-to-bottom
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = indexer;
        c.weighty = 1;
        panel.add(new JLabel(), c);


        indexer++;
    }

但我需要像这张图片的结果:

view image

我不想更改JLabel的尺寸并更改标签数量。

2 个答案:

答案 0 :(得分:2)

不确定在此处动态添加标签的含义。

对我来说,动态添加组件就是添加它 运行。以下示例演示了这一点 MigLayout经理:

package com.zetcode;

import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

import net.miginfocom.swing.MigLayout;

/*
Demonstrating dynamic addition of labels 
with MigLayout manager.

Author: Jan Bodnar
Website: zetcode.com
 */
public class MigLayoutDynamicLabelsEx extends JFrame {

    private int counter = 0;

    public MigLayoutDynamicLabelsEx() {

        initUI();
    }

    private void initUI() {

        MigLayout layout = new MigLayout("wrap 4");
        setLayout(layout);

        JButton addBtn = new JButton("Add");
        addBtn.addActionListener((ActionEvent e) -> {
            JLabel lbl = createLabel();
            add(lbl, "w 100lp, h 30lp");
            pack();
        });

        add(addBtn);
        add(createLabel(), "w 100lp, h 30lp");
        add(createLabel(), "w 100lp, h 30lp");
        add(createLabel(), "w 100lp, h 30lp");

        pack();

        setTitle("MigLayout dynamic example");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private JLabel createLabel() {

        counter++;
        String text = "#table no." + counter;

        JLabel lbl = new JLabel(text);
        lbl.setBorder(BorderFactory.createEtchedBorder());

        return lbl;
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {
            MigLayoutDynamicLabelsEx ex = new MigLayoutDynamicLabelsEx();
            ex.setVisible(true);
        });
    }
}

一开始,有按钮和三个标签。点击 在按钮上为布局添加新标签。 wrap 4约束 每行创建4列。使用pack()方法重新组织窗口。

截图:

Screenshot of the example

答案 1 :(得分:1)

我认为你没有正确设置gridx和gridy,下面的代码希望可以解决你的问题:

Fiz