Reputation: 11
I have a matrix of JButton[][]
. I try to add ActionListener
to the buttons which stores the index of the button.
I need to make a game.
The first click shows from which button should I step and the second shows where to step.
Upvotes: 0
Views: 3266
Reputation: 168825
I try to add ActionListener to the buttons which stores the index of the button.
In this case, you might simply get for the object of the event ActionEvent.getSource()
then iterate the button array until that object equals the current indices. See the findButton(Object)
method for implementation.
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);
}
}
Upvotes: 2
Reputation: 48258
What you need can be achieved in several ways, using HashMaps, 2D Arrays, etc etc... here is my suggestion:
Inheritance: you need now a Button with 2 properties that are not defined by default (col and row)
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;
}
}
you have for sure a Panel where you can add JButtons, now add instead a MatrixButton
panel.add(MatrixButton);
then add the actionlistener
button1.addActionListener(this);
and when you click you get the position coordinates by doing
@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
}
}
Upvotes: 2
Reputation: 23614
Create a method in your class that accepts an index
public void handleClick(int r, int c) { ... }
when you create your buttons add an action listener which calls this method with the correct indices:
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));
});
});
Upvotes: 0
Reputation: 4122
You can set the button's text to be the relevant index:
//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));
}
}
and then you can check what the button's index is:
//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();
}
very similarly for the second click.
Upvotes: 0