0

How do you Make a random image appear when i click the button? What do I need to add to view so the images will actually change when i click the button

Class ButtonListener:

public class ButtonListener implements ActionListener {

    private Model mod;
    public ButtonListener(Model _m){
        mod = _m;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int x = mod.random();
        if (x == 1) {
            JLabel L1 = new JLabel();
            JLabel L2 = new JLabel();
            JLabel L3 = new JLabel();
            L1.setIcon(new ImageIcon ("Images/Green.png"));
            System.out.println("1");
        }
        else if (x == 2) {
            JLabel L1 = new JLabel();
            L1.setIcon(new ImageIcon("Images/Purple.png"));
            System.out.println("2");
        }
        else {
            JLabel L1 = new JLabel();
            L1.setIcon(new ImageIcon("Images/Red.png"));
            System.out.println("3");
        }
    }
}

Class View:

public class View {

    public View() {
        Model _m = new Model();
        JFrame f = new JFrame("....");
        JPanel p = new JPanel(new GridLayout(2, 3));
        JLabel L1 = new JLabel();
        JLabel D = new JLabel();
        JLabel L2 = new JLabel();
        JLabel L3 = new JLabel();
        JButton B = new JButton("Spin");

        p.add(L2);
        p.add(L3);
        p.add(L1);
        p.add(D);
        p.add(B);
        B.addActionListener(new ButtonListener(_m));
        f.add(p);
        f.pack();
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Class Model:

public class Model {

    public Model(){
    }

    public int random(){
    Random rand = new Random();
        return rand.nextInt(4);
    }
}
TimeToCode
  • 901
  • 2
  • 16
  • 34
Nestlewater
  • 133
  • 8

1 Answers1

1

Your code appears to be trying to create an M-V-C like program, and if so, then your model needs

  1. state (i.e., a field or fields)
  2. ability to accept and notify listeners of change so that when one of its "bound" fields changes, the view can be notified, either directly (e.g., the view itself has a listener registered with the model) or indirectly (e.g., the controller has the listener registered with the model, and then when notified it -- the controller -- changes the view).

When I've done this, I've given my Model a SwingPropertyChangeSupport field as well as methods to allow other classes to add and remove PropertyChangeListeners to this support object. Then my bound fields, here a field representing the random int, has a setter method, and within this method, I have my support object notify all the listeners it holds by calling one of its firePropertyChange(...) methods.

For example, please check out my answer to a similar question here: Using a JFileChooser with Swing GUI classes and listeners

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373