質問

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