2016-12-08 8 views
0

私はJButton[][]の行列を持っています。私はボタンのインデックスを格納するボタンにActionListenerを追加しようとします。クリックされたJButtonのインデックスを取得する方法は?

私はゲームをする必要があります。

最初のクリックではどのボタンからステップし、2番目のステップでどこにステップするかが示されます。

+0

あなたは答えを理解したのですか? – ItamarG3

+0

相続に関する知識がありますか? –

+0

* "ボタンのインデックスを格納するボタンにActionListenerを追加しようとしました。" *ボタンのインデックスを格納するボタンにActionListenerを追加しようとしました。この場合、イベント 'ActionEvent.getSource()'に対応するコンポーネントを要求し、そのコンポーネントが現在のインデックスと等しくなるまでボタン配列を反復することができます。 –

答えて

2

をHashMaps、2D配列などを使用していくつかの方法で達成することができます。ここに私の提案があります:

継承:あなたは今の代わりにMatrixButtonを追加し、今あなたがJButtonが追加することができパネル確かに持っているデフォルト(COLと行)で定義されていない2つのプロパティ

class MatrixButton extends JButton { 
    private static final long serialVersionUID = -8557137756382038055L; 
    private final int row; 
    private final int col; 

    public MatrixButton(String t, int col, int row) { 
    super(t); 
    this.row = row; 
    this.col = col; 
    } 

    public int getRow() { 
    return row; 
    } 

    public int getCol() { 
    return col; 
    } 
} 

とボタンが必要

panel.add(MatrixButton); 

その後、ActionListenerを追加

button1.addActionListener(this); 

、あなたが位置を取得する]をクリックしたときに、私は、ボタンのインデックスを保存するボタンにActionListenerを追加しよう

@Override 
    public void actionPerformed(ActionEvent ae) { 
    if (ae.getSource() == this.button1) { 
     System.out 
      .println(((MatrixButton) ae.getSource()).getRow() + "," + ((MatrixButton) ae.getSource()).getCol()); 
    } else if (ae.getSource() == this.button2) { 
     // TODO 
    } else if (ae.getSource() == this.button3) { 
     // TODO 
    } 
    } 
+0

'get' /' putClientProperty' :-) – mKorbel

0

あなたはボタンのテキストは、関連する指標になるように設定することができます

//while creating the buttons 
for(int i = 0; i<buttons.length;i++){ 
    for(int j = 0; j<buttons[i].length;j++){  
     //create the button 
     buttons[i][j] = new JButton((""+i*buttons.length+j)); 
    } 
} 

、その後、あなたはボタンのインデックスが何であるかを確認することができます。

//for the first click 
try{ 
    int from = Integer.parseInt(button.getText());// get the button index as int from the text 
}catch(Exception e){ 
    e.printStackTrace(); 
} 

非常に同様もう一度クリックするため。

0

あなたは、ボタンを作成するときに、正しいインデックスでこのメソッドを呼び出すアクションリスナーを追加指数

public void handleClick(int r, int c) { ... } 

を受け入れ、あなたのクラスのメソッドを作成しますことができます必要なもの

import java.util.stream.IntStream; 

buttons = new JButton[rowSize][colSize]; 
IntStream.range(0, rowSize).forEach(r -> { 
    IntStream.range(0, colSize).forEach(c -> { 
     buttons[r][c] = new JButton(String.format("%d, %d", r, c)); 
     buttons[r][c].addActionListener(e -> handleClick(r, c)); 
    }); 
}); 
+0

次に、 'get' /' putClientProperty' :-)をforEachの中に追加します。 – mKorbel

2

を行うことで調整します。

この場合、イベントオブジェクトActionEvent.getSource()を取得し、そのオブジェクトが現在のインデックスと等しくなるまでボタン配列を反復することができます。実装については、findButton(Object)メソッドを参照してください。

enter image description here

import java.awt.*; 
import java.awt.event.*; 
import java.awt.image.BufferedImage; 
import javax.swing.*; 
import javax.swing.border.EmptyBorder; 

public class ButtonArrayIndices { 

    private JComponent ui = null; 
    private JButton[][] buttonArray = new JButton[10][5]; 
    JLabel output = new JLabel("Click a button"); 

    ButtonArrayIndices() { 
     initUI(); 
    } 

    private void findButton(Object c) { 
     for (int x = 0; x < buttonArray.length; x++) { 
      for (int y = 0; y < buttonArray[0].length; y++) { 
       if (c.equals(buttonArray[x][y])) { 
        output.setText(x + "," + y + " clicked"); 
        return; 
       } 
      } 
     } 
    } 

    public void initUI() { 
     if (ui != null) { 
      return; 
     } 

     ui = new JPanel(new BorderLayout(4, 4)); 
     ui.setBorder(new EmptyBorder(4, 4, 4, 4)); 

     ActionListener buttonListener = new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       findButton(e.getSource()); 
      } 
     }; 

     JPanel buttonPanel = new JPanel(new GridLayout(0, 10, 2, 2)); 
     ui.add(buttonPanel, BorderLayout.CENTER); 
     BufferedImage bi = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB); 
     ImageIcon ii = new ImageIcon(bi); 
     Insets margin = new Insets(0, 0, 0, 0); 
     for (int y = 0; y < buttonArray[0].length; y++) { 
      for (int x = 0; x < buttonArray.length; x++) { 
       JButton b = new JButton(); 
       buttonArray[x][y] = b; 
       b.setMargin(margin); 
       b.setIcon(ii); 
       b.addActionListener(buttonListener); 
       buttonPanel.add(b); 
      } 
     } 

     output.setFont(output.getFont().deriveFont(20f)); 
     ui.add(output, BorderLayout.PAGE_END); 
    } 

    public JComponent getUI() { 
     return ui; 
    } 

    public static void main(String[] args) { 
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (Exception useDefault) { 
       } 
       ButtonArrayIndices o = new ButtonArrayIndices(); 

       JFrame f = new JFrame(o.getClass().getSimpleName()); 
       f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
       f.setLocationByPlatform(true); 

       f.setContentPane(o.getUI()); 
       f.pack(); 
       f.setMinimumSize(f.getSize()); 

       f.setVisible(true); 
      } 
     }; 
     SwingUtilities.invokeLater(r); 
    } 
} 
+1

申し訳ありません、私にとっては 'findButton'クラス==' get'/'putClientProperty' :-) – mKorbel

関連する問題