1

I want to get the position of the JButton to have the return a value. I need the value to print out the element in an array list. I have ten elements in the array list. A GridLayout(0,2) was used to layout the buttons.

So what should I do?

                 for(int i=0;i<item.size();i++)
                {
                    JButton btn1= new JButton(item.get(i).print());

                    btn1.setPreferredSize(new Dimension(300,40));

                    panel2.setLayout(new GridLayout(0,2));

                    panel2.add(btn1, BorderLayout.NORTH);

                    content.add(panel2, BorderLayout.NORTH);

                }
            public Food selectFood(int input)
            {

                int get=0;

                if(input>0 && input< 11)
                {
                     item.get(input-1);

                }

want to get the position as an input to print the selected item.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
aaaa
  • 57
  • 1
  • 6
  • 1
    Are you looking for the button's [grid location](http://stackoverflow.com/q/7702697/230513) or it's pixel coordinates? – trashgod Nov 23 '12 at 03:07
  • 1
    As a general tip. If you need a reference to a GUI control, keep a reference rather than 'hunting' for the control later. – Andrew Thompson Nov 23 '12 at 03:17

1 Answers1

4

I remember that it can use JButton.getBounds() function, then it can use JButton.getBounds().x and JButton.getBounds().y to get its upper-left corner position.

bhuang3
  • 3,493
  • 2
  • 17
  • 17