Question

I have a method in my project, which randomly selects a button from a list and then writes the given text on it. The problem I am getting is, since it selects the button at random, it writes the text on the button even if there is already a text written on the button. what I want is, for this code to select a button and then check if there is already a text written on it and if there is, then I want it to repeat itself and select another random button, until it finds and write the given text on a button that has no text on it previously.

public class random{

    public static String text2 = "text2";

    public void static main(String[] args){
        JButton button = new JButton("Empty");
        JButton button1 = new JButton("Empty");
        JButton button2 = new JButton("Empty");

        randomButton(button,button1, button2);
    }
    public void randomButton(JButton button1, JButton button2, JButton button3){
        String text = "text";
        JButton[] arr = {button1, button2, button3};
        Random r = new Random();
        JButton b = arr[r.nextInt(arr.length)];
        b.setText(text);
        b.setEnabled(false);
    }
}

The buttons can have one of the three texts on them - Empty, text1 or text2.

What I want to do is, if the button selected at random when the method randomButton is called, I want it to check if the button selected already has text1 or text2 and if it does then I want it to reselect another random button until it finds a button that has Empty written on it and then replace it with text1.

I have tried do while loop, if statement and while loops but it won't work, maybe it because my logic is wrong but i am not sure. below, I have pasted one of my attempts but it does not work.

do {
    String text = "text";
    JButton[] arr = {button1, button2, button3};
    Random r = new Random();
    JButton b = arr[r.nextInt(arr.length)];
    if (b.getText() != "text" || b.getText() != "text2") {
        b.setText(text);
        b.setEnabled(false);
    } else {
        String text = "text";
        JButton[] arr = {button1, button2, button3};
        Random r = new Random();
        JButton b = arr[r.nextInt(arr.length)];
        b.setText(text);
        b.setEnabled(false);
    }
} while (b.getText() == text);
Was it helpful?

Solution

Have a look at this. There is a 2D array of JButton. When you click the random button, it will check to see if the button at a random index has an X or not, if not it it will set the text. Let me know if there's anything you don't understand

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

public class RandomButton {

    JButton[][] buttons = new JButton[10][10];
    JButton randomButton = new JButton("Choose Random Button");

    public RandomButton() {
        JPanel panel = new JPanel(new GridLayout(10, 10));
        initButtons(panel);

        randomButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                while (true) {
                    int[] indices = getRandom();
                    int i = indices[0];
                    int j = indices[1];
                    if (!"X".equals(buttons[i][j].getText())) {
                        buttons[i][j].setForeground(Color.BLUE);
                        buttons[i][j].setText("X");
                        break;
                    }
                }
            }
        });

        randomButton.setBorder(new LineBorder(Color.black, 5));
        panel.setBorder(new LineBorder(Color.BLACK, 5));

        JFrame frame = new JFrame("Random Button");
        frame.add(panel);
        frame.pack();
        frame.add(randomButton, BorderLayout.PAGE_END);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public int[] getRandom() {
        Random rand = new Random();
        int i = rand.nextInt(10);
        int j = rand.nextInt(10);
        int[] indices = {i, j};
        return indices;
    }

    private void initButtons(JPanel panel) {
        for (int i = 0; i < buttons.length; i++) {
            for (int j = 0; j < buttons[i].length; j++) {
                buttons[i][j] = new JButton("O");
                panel.add(buttons[i][j]);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new RandomButton();
            }
        });
    }
}

UPDATE

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

public class RandomButton {

    JButton[][] buttons = new JButton[10][10];
    JButton randomButton = new JButton("Choose Random Button");


    public RandomButton() {
        JPanel panel = new JPanel(new GridLayout(10, 10));
        initButtons(panel);
        panel.setBorder(new LineBorder(Color.BLACK, 5));

        JFrame frame = new JFrame("Random Button");
        frame.add(panel);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private class ButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JButton button = (JButton)e.getSource();
            System.out.println(button.getText());
        }
    }


    private void initButtons(JPanel panel) {
        ButtonListener listener = new ButtonListener();
        int count = 1;
        for (int i = 0; i < buttons.length; i++) {
            for (int j = 0; j < buttons[i].length; j++) {
                JButton button = new JButton(String.valueOf(count));
                buttons[i][j] = button;
                button.addActionListener(listener);
                panel.add(button);
                count++;
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new RandomButton();
            }
        });
    }
}

OTHER TIPS

package com.prasad.workouts.swing;

import java.util.Random;
import javax.swing.JButton;

public class SelectRandomBtn {

    public static String text2 = "text2";

    public static void randomButton(JButton button1, JButton button2,
            JButton button3) {
        String text = "text";
        boolean isFound = true;
        JButton[] arr = { button1, button2, button3 };
        Random r = new Random();
        for (int i = 0, length = arr.length; i < length; i ++) {
            if (arr[i].getText().isEmpty()) {
                isFound = false;
            }
        }
        do {
            JButton b = arr[r.nextInt(arr.length)];
            if (b.getText().isEmpty()) {
                isFound = true;
                System.out.println("Button Name ::: " + b.getName());
                System.out.println("Button text before replace  ::: "
                        + b.getText());
                b.setText(text);
                System.out.println("Button text after replace  ::: "
                        + b.getText());
                b.setEnabled(false);
            }
        } while (!isFound);
    }

    public static void main(String[] args) {
        JButton button1 = new JButton("Empty");
        button1.setName("button1");
        JButton button2 = new JButton();
        button2.setName("button2");
        JButton button3 = new JButton();
        button3.setName("button3");

        randomButton(button1, button2, button3);
    }
}
public class Random {
    public static void main(String[] args) {
        JButton button1 = new JButton("Empty");
        JButton button2 = new JButton("Empty");
        JButton button3 = new JButton("Empty");

        List<JButton> buttonList = new ArrayList<JButton>();
        buttonList.add(button1);
        buttonList.add(button2);
        buttonList.add(button3);

        setRandomButtonText(buttonList);
    }

    public void setRandomButtonText(List<JButton> buttonList) {
        List<JButton> availableButtons = new ArrayList<JButton>();
        for (JButton button : buttonList) {
            if (!"text".equals(button.getText()) || !"text2".equals(button.getText())) { //write your condition
                availableButtons.add(button);
            }
        }

        Random random = new Random();
        JButton selectedButton = availableButtons.get(random.nextInt(availableButtons.size()));
        selectedButton.setText("YOUR_TEXT");
        selectedButton.setEnabled(false);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top