Asuu
Asuu

Reputation: 183

grid of buttons and actionlistener

I am using the below code to create a grid of (xSize = 10) by (ySize = 10) JButtons. I am able to make changes to the buttons as long as I do it from within the class that this code is located.

However I am trying to change the text on a button from within a separate class.

public class Ocean {

public Ocean(){
}

private final int xSize = 10;
private final int ySize = 10;
private final JButton[][] buttons = new JButton[xSize][ySize];

public gameBoard() {
    for (int row = 0; row < xSize; row++) {
        for (int col = 0; col < ySize; col++) {
            buttons[row][col] = new JButton(/*space1*/);
            buttons[row][col].setText("E");
            buttons[row][col].addActionListener(new myActionListener()); 
            buttons[row][col].setPreferredSize(new Dimension(50, 50));
            playerPanel.add(buttons[row][col]);
        }
    }

}

Next Class

public class Battleship {

    int length = 4;

    public Battleship() {
    }

    public changeText(int row, int col) {
        ocean.buttons[row][col].setText("H");     need to make this work
    }

I hope this asks the question in a better way

thank you

Upvotes: 1

Views: 1156

Answers (3)

Asuu
Asuu

Reputation: 183

Here is what worked for me. In the class I used a method that called the class in its parameters.

public void placeShipAt(int row, int column, Ocean ocean) {

        ocean.buttons[row][column].setText("B");
}

Upvotes: 0

F Vicedo
F Vicedo

Reputation: 46

It's not right clear what you want to do in your code. Your example code changes the text of every button, if a button is clicked.

Maybe you want to change the text of the clicked button, then this code could help:

@Override
public void actionPerformed(ActionEvent e) {
    JButton theClickedButton = (JButton) e.getSource();
    theClickedButton.setText("M");
}

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Your question when boiled down to its essentials is simply this: How can I have one object change the state of another object?

There are many possible ways to skin this cat, but simplest is to give the one class, here Ocean (or maybe gameBoard? Your code is confusing) public methods that the outside ActionListener can call that change its state. For instance you can give the button grid-holding class a public method: setText(...) like so:

public void setText(int row, int col, String text) {
    buttons[row][col].setText(text);
}

The ActionListener can be passed a reference to this grid-holding class through a constructor parameter, allowing it to call this method when needed.

Also note that you can always get a reference to the pressed JButton through the ActionListener actionPerformed method's ActionEvent parameter. It has a getSource() method that returns a reference to the object (here JButton) that initiated the event.

If you need a more detailed solution, then please consider creating and posting a valid Minimal, Complete, and Verifiable example.

For example:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class SimpleButtonGridMain extends JPanel {
    private static void createAndShowGui() {
        SimpleButtonGrid simpleButtonGrid = new SimpleButtonGrid();

        MyButtonListener myButtonListener = new MyButtonListener();
        simpleButtonGrid.addActionListener(myButtonListener);

        JFrame frame = new JFrame("SimpleButtonGridMain");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(simpleButtonGrid);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class SimpleButtonGrid extends JPanel {
    private static final int ROWS = 10;
    private static final int COLS = ROWS;
    private JButton[][] buttons = new JButton[ROWS][COLS];

    public SimpleButtonGrid() {
        setLayout(new GridLayout(ROWS, COLS, 3, 3));
        for (int row = 0; row < buttons.length; row++) {
            for (int col = 0; col < buttons[row].length; col++) {
                String text = String.format("  [  %d,  %d  ]  ", col, row);
                JButton button = new JButton(text);
                add(button);
                buttons[row][col] = button;
            }
        }
    }

    public void addActionListener(ActionListener listener) {
        for (JButton[] jButtons : buttons) {
            for (JButton jButton : jButtons) {
                jButton.addActionListener(listener);
            }
        }
    }
}

class MyButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        JButton sourceBtn = (JButton) e.getSource();

        String message = "Button pressed: " + actionCommand;
        JOptionPane.showMessageDialog(sourceBtn, message, "Button Pressed", JOptionPane.PLAIN_MESSAGE);
        sourceBtn.setText("Pressed");
        sourceBtn.setEnabled(false);
    }
}

Upvotes: 2

Related Questions