Andriy Ukraine
Andriy Ukraine

Reputation: 27

How can I make my buttons switch without a loop?

I was wondering how I would be able to make my buttons switch in this class which I call on from a different class. But it goes in and does only one change of the buttons and that's it..

package code;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;


public class Something implements ActionListener {

    private Game G;
    private int random;
    private JButton a;
    private JButton b;
    private JButton c;
    private Font i;

    public Something(Game g, int rand, JButton d, JButton e, JButton f, Font h) {
        G = g;
        random = rand;
        a = d;
        b = e;
        c = f;
        i = h;
    }

    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        G.increment();
        if (random == 0) {
            a.setText("A");
            a.setEnabled(true);
            b.setEnabled(false);
            c.setEnabled(false);
            SuperSize(a);
            SmallerSize(b);
            SmallerSize(c);
            random = RandomNum();
            ;
        } else if (random == 1) {
            b.setText("B");
            a.setEnabled(false);
            b.setEnabled(true);
            c.setEnabled(false);
            SuperSize(b);
            SmallerSize(a);
            SmallerSize(c);
            random = RandomNum();
        } else if (random == 2) {
            c.setText("C");
            a.setEnabled(false);
            b.setEnabled(false);
            c.setEnabled(true);
            SuperSize(c);
            SmallerSize(a);
            SmallerSize(b);
            random = RandomNum();
        }
    }

    public int RandomNum() {
        Random r = new Random();
        int rand = 0;
        rand = r.nextInt(3);
        return rand;
    }

    public void SuperSize(JButton a) {
        Font myFont = i.deriveFont(Font.BOLD, i.getSize() * 4);
        a.setFont(myFont);
    }

    public void SmallerSize(JButton a) {
        a.setFont(i);
    }
}

            }

I don't know what to do , can you guys help me?

Upvotes: 1

Views: 73

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

Don't create a new instance of Random each time you call RandomNum, instead, create a instance in the constructor and continue to re-use it.

public class Something implements ActionListener {

    //...

    private Random rnd;

    public Something(Game g, int rand, JButton d, JButton e, JButton f, Font h) {
        //...
        rnd = new Random();
    }

    public int RandomNum() {
        return rnd.nextInt(3);
    }

Upvotes: 1

Related Questions