创建颜色数组,然后将其用于Jbuttons?

时间:2016-03-14 13:21:48

标签: java arrays swing jframe

我有以下代码,它是25个按钮的JFrame,每个按钮需要从颜色数组中随机分配一个颜色。我只是为颜色添加了数组,我收到了错误。

import java.awt.event.*; // Needed for ActionListener and ActionEvent
import javax.swing.*; // Needed for JFrame and JButton
import java.awt.Color;
import java.awt.Graphics;

public class ColorToggleGui extends JFrame implements ActionListener {

  // This stores all buttons
  JButton[][] buttons;
  //Stores colors
  Color[] colors;

  public ColorToggleGui(String title) {
    super(title);
    setLayout(null);

    //Allocate the size of the array
    colors = new Color[4];

        //Initialize the values of the array
    colors[0] = new Color(Color.red);
    colors[1] = new Color(Color.blue);
    colors[2] = new Color(Color.yellow);
    colors[3] = new Color(Color.green);


    buttons = new JButton[5][5];
    String[] buttonLabels = { "", "", "", "", "", "", "", "", "", "", "","","","","","","","","","","","","","","" };
    for(int row=0; row<5; row++) {
      for (int col=0; col<5; col++) {
        buttons[row][col] = new JButton(buttonLabels[row*3+col]);
        buttons[row][col].setLocation(10+col*55, 10+row*55);
        buttons[row][col].setSize(50,50);
        buttons[row][col].addActionListener(this);
        add(buttons[row][col]);
      }
    }
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(300,450);
  }


  // This is the single event handler for all the buttons
  public void actionPerformed(ActionEvent e) {
    System.out.println("Button " + e.getActionCommand() + " was pressed." );
  }

  public static void main(String args[]) {
    ColorToggleGui frame = new ColorToggleGui("Color Toggle");
    frame.setVisible(true);
  }

}

带有颜色数组的部分我收到此错误:

Error: incompatible types: java.awt.Color cannot be converted to int

为什么会发生错误?我还需要帮助一种方法来使用颜色数组随机分配每个按钮与颜色数组的颜色?我有办法做到这一点吗?

3 个答案:

答案 0 :(得分:1)

在没有Color.red

的情况下使用new Color()
colors[0] = Color.red;

如果要从rgb值(如

)生成颜色,请使用新构造函数
colors[1] = new Color(100,100,100);

颜色构造函数重载构造函数,它接受一个整数作为参数。

public Color(int i) {
        // compiled code
}

这就是你收到错误的原因

Error: incompatible types: java.awt.Color cannot be converted to int

答案 1 :(得分:1)

带有单个参数的Java Color构造函数是:

Color (int rgb)

然而,你在这里做了什么:

colors[0] = new Color(Color.red);

您提供Color object而不是int,因此收到错误java.awt.Color cannot be converted to int

你可以这样做:

colors[0] = Color.RED;

注意:最好使用Color.RED而不是Color.red。

答案 2 :(得分:0)

正如您之前提到here而没有人关闭它:

我在两个问题上都给你 一个好的答案 ,并在这里: https://stackoverflow.com/a/36004026/982161