随机JTextField黄色

时间:2014-10-07 16:51:41

标签: java arrays random jtextfield setbackground

我的设计中有9个文本字段,名为box1,box2等。我想将其中一个设为黄色。所以我确实将文本字段的名称放在一个数组中,并尝试使用Random函数来选择其中一个名称。但它不起作用。

String[] boxes = new String[]{"box1", "box2", "box3", "box4", "box5", "box6", 
    "box7", "box8", "box9"};

Random rand = new Random();
int randomint = rand.nextInt(9);
String thatBox = boxes[randomint];

thatBox.setBackground(Color.yellow);

1 个答案:

答案 0 :(得分:2)

String[]框更改为JTextField[],并将每个元素设为实际JTextField

import javax.swing.JTextField;
import java.awt.Color;
import java.util.Random;

public class SOQ10
{
   public void something()
   {
      String[] box = new String[]{"box1", "box2", "box3", "box4", "box5", "box6", 
         "box7", "box8", "box9"};

      JTextField[] boxes = new JTextField[9];

      for(int i = 0; i < 9; i++)
      {
         boxes[i] = new JTextField(box[i]);          
      }

      Random rand = new Random();
      int randomint = rand.nextInt(9);
      boxes[randomint].setBackground(Color.yellow);
   }
}