I want to add a vector of 36 JButtons into a JPanel but when I do it gives me errors and say that I can't add a vector into a JPanel. Is there any way to do that? thanks for your help.

有帮助吗?

解决方案

I'm not really big on gui in java lol aside from my old school work but I found an example that should help you out. There is a difference, they used texfields and not buttons but with effort it should work out alright for you if you follow the example. The example is the third or fourth post in the thread fyi.

link to example

其他提示

You can't add a Vector, so instead go through it with a for loop and add each individual element of the Vector.

for (JButton b : yourVector) {
    //add b to panel here
}

You could try this:

import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JPanel;

public class ListButtonPanel extends JPanel {

    private List<JButton> buttons = new ArrayList<>();

    public ListButtonPanel() {

        this.setPreferredSize(new Dimension(800, 600));
        for(int i = 1; i <= 36; i++) {
            buttons.add(new JButton("Button-" + i));
        }

        this.setLayout(new GridLayout(6, 6));
        for(JButton button : buttons) {
            this.add(button);
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top