0

Simplified: How to make String value to call specific existed JButton variable name in java?

I'm trying to make a non-ordinary Tic-Tac-Toe game...

Anyway, what I will post here is not really the whole concept of that. I just want to make it simple: I have 9 square jButtons named (3 by 3) (and maybe allow user to make 4x4, 5x5, 10x10 etc. via settings in future):

[markbox_00_00] / [markbox_00_01] / [markbox_00_02]

[markbox_01_00] / [markbox_01_01] / [markbox_01_02]

[markbox_02_00] / [markbox_02_01] / [markbox_02_02]

[btnSave] / [btnUndoActions]

where the first two digit represent the row and the next two is the column; and a save button (btnSave) and undo button(btnUndoActions).

Each markbox have default spring value of "0", when I click it turns "1"; and when I click "1" it turns "0". When you press undo button it will reset to last save.

Here is some of my simplified line of codes:

private byte markboxColLimit = 3, markboxRowLimit = 3, row, col;
private byte[][] saveNumber = new byte[markboxRowLimit][markboxColLimit];
private String buttonName;

public Astral_TicTacToe() {
initComponents();

    /* I want something like this, but using a for loop based on markboxColLimit and 
    markboxRowLimit as limits */

    markbox_00_00.setText("0");
    markbox_00_01.setText("0");
    markbox_00_02.setText("0");
    markbox_01_00.setText("0");
    markbox_01_01.setText("0");
    markbox_01_02.setText("0");
    markbox_02_00.setText("0");
    markbox_02_01.setText("0");
    markbox_02_02.setText("0");

          /* I know the line below is wrong... what I'm trying is to avoid
           * repetitiveness by looping and dynamically calling the variable
           * name of JButtons, or in other ways...
           */
    /* Attempting to make an alternative code from above (trying to make a loop instead) */

    for(row = 0; row < markboxRowLimit; row++){

        for(col = 0; col < markboxColLimit; col++){
          buttonName = "markbox_0" + Byte.toString(row) + "_0" + Byte.toString(col);

          buttonName.setText("0");
        }
    }
}

private void btnUndoActionsActionPerformed(java.awt.event.ActionEvent evt) {

    markbox_00_00.setText(Byte.toString(saveNumber[0][0]));
    markbox_00_01.setText(Byte.toString(saveNumber[0][1]));
    markbox_00_02.setText(Byte.toString(saveNumber[0][2]));
    markbox_01_00.setText(Byte.toString(saveNumber[1][0]));
    markbox_01_01.setText(Byte.toString(saveNumber[1][1]));
    markbox_01_02.setText(Byte.toString(saveNumber[1][2]));
    markbox_02_00.setText(Byte.toString(saveNumber[2][0]));
    markbox_02_01.setText(Byte.toString(saveNumber[2][1]));
    markbox_02_02.setText(Byte.toString(saveNumber[2][2]));
}

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
    saveNumber[0][0] = Byte.parseByte(markbox_00_00.getText());
    saveNumber[0][1] = Byte.parseByte(markbox_00_01.getText());
    saveNumber[0][2] = Byte.parseByte(markbox_00_02.getText());
    saveNumber[1][0] = Byte.parseByte(markbox_01_00.getText());
    saveNumber[1][1] = Byte.parseByte(markbox_01_01.getText());
    saveNumber[1][2] = Byte.parseByte(markbox_01_00.getText());
    saveNumber[2][0] = Byte.parseByte(markbox_02_00.getText());
    saveNumber[2][1] = Byte.parseByte(markbox_02_01.getText());
    saveNumber[2][2] = Byte.parseByte(markbox_02_02.getText());
}

private void markbox_00_00ActionPerformed(java.awt.event.ActionEvent evt) {
    if("0".equals(markbox_00_00.getText()))
        markbox_00_00.setText("1");
    else
        markbox_00_00.setText("0");
}

private void markbox_00_01ActionPerformed(java.awt.event.ActionEvent evt) {
    if("0".equals(markbox_00_01.getText()))
        markbox_00_00.setText("1");
    else
        markbox_00_00.setText("0");
}

....

private void markbox_02_02ActionPerformed(java.awt.event.ActionEvent evt) {
    if("0".equals(markbox_00_00.getText()))
        markbox_02_02.setText("1");
    else
        markbox_02_02.setText("0");
}

In short: how can I make String a specific variable name of JButton for calling/accessing/editing for their properties?

Example:

buttonName = markbox_01_02;

buttonName.setText("2");

is equavalent to markbox_01_02.getText("2");

I really appreciate the help, thank you...

P.S. I use to make JFrame in NetBeans Design (just click and drag the objects in palette window like JPanel, JButton, etc., so I don't type the code manually except making my own logical Method).

Community
  • 1
  • 1
Jan Jeremy
  • 43
  • 1
  • 6
  • *how can I make String to JButton?* which String? – Frakcool Jan 05 '16 at 17:03
  • 1
    try to rephrase your question as it is unclear what you're asking. Moreover, you don't need many ActionPerformed methods, one would suffice. – mxb Jan 05 '16 at 17:05
  • I second what @mxb is saying --your question is quite unclear. Also you'll want to decouple your program logic from your GUI. Create a non-GUI model that holds the state of a 3 by 3 grid of MarkBox objects, and when a button is pushed, check the state of the corresponding MarkBox object and respond according to its state, including changing its state. The state changes will then be reflected in the appearance of the GUI. – Hovercraft Full Of Eels Jan 05 '16 at 17:07
  • You probably want a JButton[][] buttons, containing 3 rows of 3 buttons. – JB Nizet Jan 05 '16 at 17:17
  • I'm not sure I understand well your problem: You want to have your TicTacToe game to have 1 or 0 when you press any button. And when you clic "undo" it will undo the last clic, am I right? – Frakcool Jan 05 '16 at 17:30
  • Hi, sorry for not being clear. About the Undo button it act like clear all edits back to origin or last saved. Now, I had rewrite some codes please take a look. I just wanna say let's forgot tic-tac-toe, but what I want to achieve is I want a loop to avoid repetitiveness and dynamically calling the variable name of JButtons. – Jan Jeremy Jan 05 '16 at 19:12
  • Example: I declare a new variable name buttonName as String type to catch "markbox_" + variableColumnNumber + "_" + variableRowNumber as variableColumnNumber and variableRowNumber incremented. As you can see there's markbox_00_00, markbox_00_01, markbox_00_02, markbox_01_00, markbox_01_01, and so on. – Jan Jeremy Jan 05 '16 at 19:14
  • @JanJeremy still unclear. If you wanna notify me or anyone in specific you can tag them and they'll get a notification, to tag someone do it as @ username (w/o space between username and `@`) just as I did with you in the 1st word of this comment :) – Frakcool Jan 05 '16 at 19:38
  • @Frakcool @mxb @Hovercraft Full Of Eels Hi @JB Nizet , sorry guys, I failed to make you understand. But want I want to know is: **is it possible to make a String a specific variable name of JButton for calling/accessing/editing for changing/getting their properties** like getText(), setText(), setBackground, and so on; I really don't know, but I heard something like using a `Map`? – Jan Jeremy Jan 06 '16 at 05:42
  • @JanJeremy probably something like [this]( http://stackoverflow.com/questions/6729605/assigning-variables-with-dynamic-names-in-java)? – Frakcool Jan 06 '16 at 05:50
  • Or [this](http://stackoverflow.com/questions/1192534/is-there-away-to-generate-variables-names-dynamically-in-java)? – Frakcool Jan 06 '16 at 05:56

1 Answers1

3

You probably need to redo your program and rephrase your question because it's kind of unclear where you're stuck that's why I wrote this answer as a Community Wiki.

The following program creates a GridLayout for the board and add 2 JButtons below it which contain "Save" and "Undo" buttons.

Whenever you press a button it will change it's text to 0 or 1 depending on the previous state of the button, and "Undo" button will undo last clic the same way, if it was 0 it will become 1 and viceversa.

I guess you should read How to write an ActionListener before copy-pasting this example, understand what it says and try to understand how this program works.

The logic to "Save" button is up to you 'cause I'm not sure what you wanna do there and I'm not gonna write all the code for you. This is made only for you to get an idea on how to handle events.

Also, the logic to end the game is left to you for the same reasons as the "Save" button.

I wish I knew how to record my screen in Ubuntu and save as GIF but here's a screenshot on how this program looks like:

enter image description here

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TicTacToe implements ActionListener {
    JFrame frame;
    JButton buttons[];
    JPanel pane, buttonPane;
    boolean pressed[];
    JButton save, undo;
    int n = -1;

    public void actionPerformed(ActionEvent e) {
        for (int i = 0; i < buttons.length; i++) {
            if(e.getSource() == buttons[i]) {
                pressed[i] = !pressed[i];
                buttons[i].setText(pressed[i] ? "1" : "0");
                n = i;
                break;
            }
        }
    }

    public TicTacToe () {
        frame = new JFrame("Tic Tac Toe Game");
        buttons = new JButton[9];
        pane = new JPanel(new GridLayout(3, 3));
        pressed = new boolean[9];
        buttonPane = new JPanel(new FlowLayout());
        save = new JButton("Save");
        undo = new JButton("Undo");

        for (int i = 0; i < buttons.length; i++) {
            buttons[i] = new JButton("0");
            pressed[i] = false;
        }

        for (JButton b : buttons) {
            b.addActionListener(this);
            pane.add(b);
        }

        undo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if (n == -1) {
                    return;
                }
                pressed[n] = !pressed[n];
                buttons[n].setText(pressed[n] ? "1" : "0");
            }
        });

        buttonPane.add(save);
        buttonPane.add(undo);

        frame.add(pane, BorderLayout.PAGE_START);
        frame.add(buttonPane, BorderLayout.CENTER);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    public static void main (String args[]) {
        new TicTacToe();
    }
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89