mardi 15 décembre 2015

Selecting a JButton and not letting it's value change

A test class created from my original code. How would I prevent a selected JButton changing it's value, and allow the other JButtons to be rolled. Is there a way to prevent more than one JButton from changing.

Test Class

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JFrame {

    JButton[] pic = new JButton[5];
    JPanel panel = new JPanel();
    JButton throwDice = new JButton("Throw");
    ImageIcon img;

    Die[] dieH = new Die[5];
    Dice dice = new Dice();

    Test(String title) {
        super(title);
        setSize(400, 400);
        setLayout(new BorderLayout());
        add(panel, BorderLayout.CENTER);
        components();
        throwHandle();
    }

    public static void main(String[] args) {
        Test test = new Test("Test");
        test.setVisible(true);
    }

    public void components() {
        for (int i = 0; i < 5; i++) {
            pic[i] = new JButton("");
            pic[i].setPreferredSize(new Dimension(50, 50));
            panel.add(pic[i]);
        }
        panel.add(throwDice);
    }

    public void throwHandle() {
        throwDice.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dieH = dice.roll();

                for (int i = 0; i < 5; i++) {
                    pic[i].setIcon(dieH[i].getDieImage());
                    System.out.println(dieH[i].getValue());
                }
            }
        });
    }
}

Die Class

import javax.swing.*;

public class Die {

    int faceValue;
    ImageIcon img;

    public ImageIcon getDieImage() {
        return img;
    }

    public void setImage(int fValue) {

        for (int i = 0; i < fValue; i++) {
            img = new ImageIcon("./src/images/" + (i + 1) + ".png");
        }
    }

    public void setValue(int v) {
        this.faceValue = v;
        setImage(faceValue);
    }

    public int getValue() {
        return faceValue;
    }
}

Dice Class

import java.util.Random;

public class Dice {

    Die[] diceArray = new Die[];

    public Dice() {
        for (int i = 0; i < diceArray.length; i++) {
        diceArray[i] = new Die();
        diceArray[i].setValue(i + 1);
        }
     }

    public Die[] roll() {

        Random rand = new Random();

        int randomNum;
        Die[] roll = new Die[5];
        for (int i = 0; i < 5; i++) {
            randomNum = rand.nextInt((5 - 1) + 1);
            roll[i] = diceArray[randomNum];
        }
        return roll;
    }
}




Aucun commentaire:

Enregistrer un commentaire