mercredi 18 novembre 2015

Random color to several jbuttons

I need to assign a random color to each of 16 jbuttons, the way my code is currently, I am getting a random color but that same color is given to all 16 jbuttons. I understand why this is happening but I have no idea how to fix it. Thanks a ton

package code;

import java.awt.Color;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GameG implements Runnable {

    public static JButton jba;
    public static JPanel jp;

@Override
public void run(){

    JFrame jf = new JFrame("Keybricks");
    Random rnd = new Random();

    jp = new JPanel();

    jp.setLayout(new GridLayout(4, 1));

    jf.setSize(300, 600);
    jf.setVisible(true);
    jf.setResizable(false);
    jf.add(jp);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ArrayList<Color> colors = new ArrayList<>();

    colors.add(Color.RED);
    colors.add(Color.BLUE);
    colors.add(Color.GREEN);
    colors.add(Color.YELLOW);

    Color randomColor = colors.get(rnd.nextInt(colors.size()));

    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    ArrayList<Character> letters = new ArrayList<>(); {

    for (char c : alphabet.toCharArray()) {
          letters.add(c);
        }

    char randomLetter = letters.get(rnd.nextInt(letters.size()));

    ArrayList<JButton> buttons = new ArrayList<>();

    for (int i = 0; i < 16; i++){
        JButton jb = new JButton();
        buttons.add(jb);
        jp.add(jb);
    }

    JButton randomJButton = buttons.get(rnd.nextInt(buttons.size()));


    for (JButton button : buttons){
        button.setBackground(randomColor);
        button.setOpaque(true);
    }




Aucun commentaire:

Enregistrer un commentaire