【问题标题】:Make random JTextField Yellow使随机 JTextField 黄色
【发布时间】:2014-10-07 16:51:41
【问题描述】:

我的设计中有 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);

【问题讨论】:

  • 呃,JTextField 呢?
  • 很抱歉解释不佳。我的设计中有 9 个名为 box1、box2 等的文本字段。我想将其中一个设为黄色。
  • 好的,其他人回答你的问题了吗?因为我仍然很困惑
  • 嗯,它看起来像答案,但它没有编译所以没有。
  • Strings没有setBackground()属性,建议你去学习

标签: java arrays random jtextfield setbackground


【解决方案1】:

将您的 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);
   }
}

【讨论】:

  • 你确定那是 OP 想要做的吗?我只是很困惑,因为他提到了 JTextFields,但我只是字符串
猜你喜欢
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
  • 1970-01-01
相关资源
最近更新 更多