0

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);
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
Seeker
  • 509
  • 4
  • 19
  • Note that you are missing some `{}` after the `if`, can't you test `b.getText()` top see if there's text? –  Feb 14 '14 at 12:26
  • Loop over all buttons and add available ones to another temporary array. Then apply random selection on it. Your do-while may not end till the end of time – Mustafa Genç Feb 14 '14 at 12:27
  • @RC, sorry if wasn't suppose to be just b, if was suppose to be b.getText(). thanks for pointing it out. but this does work, and I did add the {}, I had to rewrite it here and I forgot to put the {}. – Seeker Feb 14 '14 at 12:29
  • @MustafaGenç, could you show me how to add another array? and also, will that check if the button selected already has one of the given text? – Seeker Feb 14 '14 at 12:31
  • @Jayaprasad, I changed it to b.getText(), it was suppose to be like that but since I had to write it again on stackoverflow, since it won't allow me to copy paste, I forgot to write b.getText(). – Seeker Feb 14 '14 at 12:32
  • Don't use `==` and `!=` to compare Strings. Use `equals`. See [How Do i Compare Strings in Java](http://stackoverflow.com/q/513832/2587435) – Paul Samsotha Feb 14 '14 at 12:38
  • k, but doesn't that mean the same thing and will provide the same result? – Seeker Feb 14 '14 at 12:39
  • `public void static` this CANNOT be – Mustafa Genç Feb 14 '14 at 12:52

3 Answers3

1
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);
    }
}
Mustafa Genç
  • 2,569
  • 19
  • 34
  • Genc, thanks for the example. Going to try it out and I will let know how it goes. Thanks once again. – Seeker Feb 14 '14 at 12:42
  • Genc, I am getting en error on the word List in List availableButtons = new ArrayList(); – Seeker Feb 14 '14 at 12:46
  • import it! don't you use an IDE? If you are beginner, read some docs. get used to work with lists. – Mustafa Genç Feb 14 '14 at 12:48
  • I am using eclipse, JDK 1.6 – Seeker Feb 14 '14 at 12:52
  • Download Eclipse from http://www.eclipse.org/downloads/ . You need to get warned! – Mustafa Genç Feb 14 '14 at 12:55
  • I changed the List to Arraylist and now it doesn't give any error on that but it still gives me an error when I add items to the array buttonList.add(button3); the error i am getting is Syntax error on token "button1", VariableDeclaratorId expected after this token and same for all the other buttons – Seeker Feb 14 '14 at 12:55
  • Your main method is `public void static main`. You really need to read some docs. – Mustafa Genç Feb 14 '14 at 12:56
  • You will figure it out. – Mustafa Genç Feb 14 '14 at 13:03
  • @user3288493 the answered code will work. For the error you are getting please see the imports added in your class. You need to add List interface from java.util class. Simple way is copy the answered code to your class and if you are using eclipse IDE, press the keys shift + crtl + o which will added necessary imports – AJJ Feb 14 '14 at 13:08
  • Read the java docs on collections. You can google it. You need to read the java docs before making use of the classes of java... – AJJ Feb 14 '14 at 13:09
1
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);
    }
}
AJJ
  • 3,570
  • 7
  • 43
  • 76
1

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();
            }
        });
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Hi, peeskillet, I was just playing around with this code, can I ask you a question. You know where you have said if (!"X".equals(buttons[i][j].getText())), if this is true then it will set the text of the button to X, is it also possible to check if the button selected does not contain one or more of the two given text and then set the button text to X if it doesn't contain the texts. e.g. if the button does not contain X or Y then set the text to X, else repeat and find another random button and check the same thing again and if the button does not contain X or Y then set the text to X. – Seeker Feb 14 '14 at 14:02
  • Yea just use two statements in the `if`, i.e `if (!"X".equals(...) && !"Y".equals(...))` – Paul Samsotha Feb 14 '14 at 14:07
  • Thanks that it, I was using || sign instead of && and it wasn't working. Also, how can I refer to individual buttons, so for example, if I want to set the text of some of the buttons to something different instead of O to start with how can I do that? – Seeker Feb 14 '14 at 14:18
  • Are you trying to access it from an actionListener, like when the O button is pressed, and not the randomButton? To do that, in the `actionPerformed` just use `JButton button = (Jbutton)e.getSource();`. Using the same listener for all the buttons, by using the above code, whichever button is pressed will be the one reference by getting which button fired the event – Paul Samsotha Feb 14 '14 at 14:28
  • Yes, so when each individual button is pressed. – Seeker Feb 14 '14 at 14:29
  • I edited the above comment. `button` will be the `JButton` that is clicked. Then do something with it – Paul Samsotha Feb 14 '14 at 14:30
  • In the `actionPerformed` of your `ActionListener` the `e` is the `e` from `public void actionPerfomed(ActionEvent e)` – Paul Samsotha Feb 14 '14 at 14:38
  • You need to add a listener to all the buttons though. Just created a custom `ActionListener`. All post an example – Paul Samsotha Feb 14 '14 at 14:40
  • I tried that but it didn't work but its working now, I forgot to change (Jbutton)e.getSource(); to (JButton)e.getSource(); . Thanks it works now. – Seeker Feb 14 '14 at 14:42
  • When I press a button it does nothing. – Seeker Feb 14 '14 at 14:43
  • You need to add a different listener for the x buttons. You can't use the same listener for random button. You also need to add the new listener to all the buttons. See my **UPDATE**. I took out the random stuff just to shorten the code. You can see the custom `ButtonListener` – Paul Samsotha Feb 14 '14 at 14:49
  • @peeskiller, what is the best way to write code? for example, why do you have your main class at the end and everything above it. – Seeker Feb 14 '14 at 16:00
  • You can put the `main` method anywhere. Some prefer the beginning, i prefer the bottom because it's of the least importance. I think the bottom is preferred. As far as everything else, usually the correct format is 1) data fields 2) constructor 3) methods.. in that order. For everything else, I just order them as I go along. If a method is dependent on another, I try to couple them in the same location. – Paul Samsotha Feb 14 '14 at 16:04
  • So the preferred / a good layout to code is class - constructor - methods - then main class. is it how OO programming should be written in? – Seeker Feb 14 '14 at 16:12
  • and also, is it good to have many methods that will make the code in the constructor body much shorter. (for OO programming). – Seeker Feb 14 '14 at 16:14
  • Second question, yes. Anywhere you have repetitve code, shorten it with a method. First question, it's not a main class, it's a `main` _method_. And normally you don't have a `main` in all your classes just the running program, but yeah, that's how OOP should be written – Paul Samsotha Feb 14 '14 at 16:18
  • Thanks for clarifying that. btw, have you got any tips that I should consider to be better at OO. tips on what I should avoid and what I should do in my programs to make my code efficient. – Seeker Feb 14 '14 at 16:21
  • That a pretty broad question. I would just go through [**these tutorial**](http://docs.oracle.com/javase/tutorial/reallybigindex.html) and you will pick up on good practices. Can't go wrong writing the Oracle way. – Paul Samsotha Feb 14 '14 at 16:23
  • Thanks for the link, going to read it now and hopefully that will give me a better understanding of OO and once again, thanks for your all help. – Seeker Feb 14 '14 at 16:35
  • btw, I am confused with the term, interface in OO. I have read many docs on it but I still can't seem to grasp the correct concept of what it does or mean. Could you give me a brief definition of what it does / mean? please. – Seeker Feb 14 '14 at 16:39
  • Again that question is too broad, Almost anything you want to find out about standard java can be found in that link. Like [interfaces](http://docs.oracle.com/javase/tutorial/java/concepts/interface.html). Please do some research. This is not the proper platform for this type of discussion. It's more a q & a, meaning specific programming questions get specific answers. – Paul Samsotha Feb 14 '14 at 16:42