2016-12-08 6 views
0

У меня есть матрица JButton[][]. Я пытаюсь добавить ActionListener к кнопкам, в которых хранится индекс кнопки.Как получить индексы щелкнутого JButton?

Мне нужно сделать игру.

Первый щелчок показывает, с какой кнопкой я должен ступить, а второй показывает, где шаг.

+0

ты понял ответ? – ItamarG3

+0

У вас есть знания с наследованием ??? –

+0

* «Я пытаюсь добавить ActionListener к кнопкам, в которых хранится индекс кнопки.» * Я пытаюсь добавить ActionListener к кнопкам, в которых хранится индекс кнопки. В этом случае вы можете запросить компонент, соответствующий событию «ActionEvent.getSource()», а затем перебрать массив кнопок, пока этот компонент не будет равен текущим индексам. –

ответ

2

Что вам нужно может может быть достигнуто несколькими способами, используя HashMaps, 2D-массивы и т. д. и т. д. ... вот мое предложение:

Наследование: вам нужно теперь кнопки с 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; 
    } 
} 

вы должны наверняка панель, где вы можете добавить JButtons, теперь добавить вместо него MatrixButton

panel.add(MatrixButton); 

затем добавить ActionListener

button1.addActionListener(this); 

и при нажатии вы получаете координаты положения, делая

@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' :-) inside forEach – mKorbel

2

Я пытаюсь добавить ActionListener к кнопкам, которые хранят индекс кнопки.

В этом случае вы можете просто получить объект объекта 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

Смежные вопросы