2012-11-23 128 views
1

我想获得JButton的位置以获得返回值。我需要该值来打印数组列表中的元素。数组列表中有十个元素。使用GridLayout(0,2)布局按钮。如何获得JButton的位置?

那我该怎么办?

    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); 

       } 

希望获得该位置作为输入来打印所选项目。

+0

你有任何代码? – Rayshawn

+1

你在寻找按钮的[网格位置](http://stackoverflow.com/q/7702697/230513)还是它的像素坐标? – trashgod

+1

作为一般提示。如果您需要对GUI控件的引用,请稍后参考而不是“搜索”控件。 –

回答

4

我记得它可以使用JButton.getBounds()函数,那么它可以使用JButton.getBounds().xJButton.getBounds().y来得到它的左上角位置。

+2

对于这个位置,'JButton#getLocation()'就足够了,因为它返回表示组件在其容器中的位置的x,y Point。 –

+0

我看到..非常感谢:) – bhuang3

+0

您应该使用getX和getY,因为它不会导致堆分配。 – Ungeheuer