1、遍历查找,速度相对慢,不过对于小规模数组来说不是问题:
02 | import java.awt.event.*; |
07 | * <a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a> Jeky |
09 | public class ShowIndexDemo extends JFrame implements ActionListener { |
11 | public static final int BUTTON_ARRAY_SIZE = 5 ; |
13 | public ShowIndexDemo() { |
14 | super ( "Show Index Demo" ); |
15 | this .setLayout( new GridLayout(BUTTON_ARRAY_SIZE, BUTTON_ARRAY_SIZE)); |
16 | buttons = new JButton[BUTTON_ARRAY_SIZE][BUTTON_ARRAY_SIZE]; |
17 | for ( int i = 0 ; i < BUTTON_ARRAY_SIZE; i++) { |
18 | for ( int j = 0 ; j < BUTTON_ARRAY_SIZE; j++) { |
19 | buttons[i][j] = new JButton( "B" ); |
20 | buttons[i][j].addActionListener( this ); |
21 | this .add(buttons[i][j]); |
26 | this .setDefaultCloseOperation(EXIT_ON_CLOSE); |
30 | public void actionPerformed(ActionEvent e) { |
31 | for ( int i = 0 ; i < BUTTON_ARRAY_SIZE; i++) { |
32 | for ( int j = 0 ; j < BUTTON_ARRAY_SIZE; j++) { |
33 | if (buttons[i][j] == e.getSource()) { |
34 | JOptionPane.showMessageDialog( this , "(" + i + "," + j + ")" ); |
40 | public static void main(String[] args) { |
41 | new ShowIndexDemo().setVisible( true ); |
43 | private JButton[][] buttons; |
2、新建一个类继承JButton
02 | import java.awt.event.*; |
07 | * <a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a> Jeky |
09 | public class ShowIndexDemo extends JFrame implements ActionListener { |
11 | public static final int BUTTON_ARRAY_SIZE = 5 ; |
13 | public ShowIndexDemo() { |
14 | super ( "Show Index Demo" ); |
15 | this .setLayout( new GridLayout(BUTTON_ARRAY_SIZE, BUTTON_ARRAY_SIZE)); |
16 | buttons = new JButton[BUTTON_ARRAY_SIZE][BUTTON_ARRAY_SIZE]; |
17 | for ( int i = 0 ; i < BUTTON_ARRAY_SIZE; i++) { |
18 | for ( int j = 0 ; j < BUTTON_ARRAY_SIZE; j++) { |
19 | buttons[i][j] = new IndexButton( "B" , i, j); |
20 | buttons[i][j].addActionListener( this ); |
21 | this .add(buttons[i][j]); |
26 | this .setDefaultCloseOperation(EXIT_ON_CLOSE); |
30 | public void actionPerformed(ActionEvent e) { |
31 | IndexButton button = (IndexButton) e.getSource(); |
32 | JOptionPane.showMessageDialog( this , "(" + button.x + "," + button.y + ")" ); |
35 | public static void main(String[] args) { |
36 | new ShowIndexDemo().setVisible( true ); |
39 | public static class IndexButton extends JButton { |
41 | public IndexButton(String text, int x, int y) { |
49 | private JButton[][] buttons; |