Question

is it possible to avoid overwriting a button text. for example, in my program I have three buttons;

JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();

Then I have a piece of code that randomly selects one of these buttons and write the given text/s on it, now I want is, once this code has chosen 1 button and written the text, I want it to not count this button in the next random selection or check if a certain text is already on the button then choose another button to write the text on.

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);
Was it helpful?

Solution 2

Create a list where you have the remaining buttons

List<JButton> remaining = new ArrayList( Arrays.asList( arr ) );

Each time you set a text on a button remove that button from you list

void removeButton(JButton b, String text) {
  remaing.remove(b);
  b.setText(text);
  b.setEnabled(false);
}

then call random on the actual size

JButton b = remaining.get(r.nextInt(remaining.size()));

OTHER TIPS

  1. Create a List containing your buttons.
  2. You can use the Collections.shuffle() method to randomize the buttons.
  3. Every time you need a random button you can access button(0) and then remove the button from the List.

An if statement should work here:

String str = b.get Text();
if(str.size()==0){
    //Give text value 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top