View Single Post
  #2 (permalink)  
Old 08-02-2007, 11:26 PM
hardwired hardwired is online now
Senior Member
 
Join Date: Jul 2007
Posts: 1,146
hardwired is on a distinguished road
Code:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ComponentLocation implements ActionListener { JButton[][] buttons = new JButton[4][4]; public void actionPerformed(ActionEvent e) { JButton button = (JButton)e.getSource(); Point gridLoc = getArrayLocation(button); System.out.println("gridLoc = [" + gridLoc.x + ", " + gridLoc.y + "]"); } private Point getArrayLocation(JButton target) { Point p = new Point(-1, -1); for(int j = 0; j < buttons.length; j++) { for(int k = 0; k < buttons[j].length; k++) { if(buttons[j][k] == target) { p.setLocation(j, k); return p; } } } return p; } private JPanel getContent() { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weighty = 1.0; gbc.weightx = 1.0; for(int j = 0; j < buttons.length; j++) { for(int k = 0; k < buttons[j].length; k++) { int n = j*buttons[j].length + k + 1; buttons[j][k] = new JButton("Button " + n); buttons[j][k].addActionListener(this); gbc.gridwidth = (k < buttons[j].length-1) ? 1 : GridBagConstraints.REMAINDER; panel.add(buttons[j][k], gbc); } } return panel; } public static void main(String[] args) { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(new ComponentLocation().getContent()); f.setSize(400,400); f.setLocation(200,200); f.setVisible(true); } }
Reply With Quote