-3
JButton btn = new JButton();
JButton[][] boutons = {{btn, btn, btn, btn, btn, btn, btn, btn, btn}, {btn, btn, btn, btn, btn, btn, btn, btn, btn}, {btn, btn, btn, btn, btn, btn, btn, btn, btn}, {btn, btn, btn, btn, btn, btn, btn, btn, btn}, {btn, btn, btn, btn, btn, btn, btn, btn, btn}, {btn, btn, btn, btn, btn, btn, btn, btn, btn}, {btn, btn, btn, btn, btn, btn, btn, btn, btn}, {btn, btn, btn, btn, btn, btn, btn, btn, btn}, {btn, btn, btn, btn, btn, btn, btn, btn, btn}};


public Fenetre() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new GridLayout(9, 9));
        setContentPane(contentPane);

        for (int ligne=0;ligne<boutons.length;ligne++) {
            for(int colone=0;colone<boutons[ligne].length;colone++) {
                JButton bouton = boutons[ligne][colone];
                bouton.setName(String.valueOf(ligne) + " : " + String.valueOf(colone));
                System.out.println(String.valueOf(ligne) + " " + String.valueOf(colone));
                bouton.addActionListener(this);
                contentPane.add(bouton);
            }
        }


}

I want to display 9x9 Jbuttons (which are in the array of JButtons) and set a name at each JButton, to retrieve their information later. But... I have only one JButton in my JPanel.....

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • This needs 81 buttons.. – Andrew Thompson Apr 10 '16 at 12:36
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Apr 10 '16 at 12:37

1 Answers1

2

Cause of problem:

All the elements of your array point to the same button btn

As such, when you add them, you only add the same button, which is already present in the panel. Hence, you see only 1 button.


How to solve it:

  • In your array declaration, replace all btns with new JButton(). You can do this easily by using the replace function of your IDE.

or

  • Just declare the array like:

    JButton[][] boutons = new JButton[9][9];
    

    and add this line in you for loop:

    bouton = new JButton();
    
dryairship
  • 6,022
  • 4
  • 28
  • 54