Search code examples
javaswinglistjbuttonjlabel

How do you set all JLabels made in a list to change what is shown


FIXED

I'm sorry for the bad title, but I spend 5 minuits on it and can't phrase it better sorry.

I need to have it so that if you press JButton all, it takes the image in all2 and also puts that into JLabel label (made with a list)

I put the JLabel all2 above map() because if I didn't, "ImageIcon setAll can't be resolve". I didn't put JLabel label above map() because it messes up with the creation of the 100 JLables made with the list listofLabels. All that it would show was one sigle Label.enter image description here enter image description here

public class mapMaker {

ArrayList<JLabel> listofLabels = new ArrayList<JLabel>(100);
ImageIcon forest = new ImageIcon("resources/terrains/forest.jpg");
ImageIcon wood = new ImageIcon("resources/terrains/wood.jpg");

JFrame frame = new JFrame("D&D");
JLabel all2=new JLabel( wood);



public map() {
    int a=0,b=50;
    JFrame.setDefaultLookAndFeelDecorated(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(100,0,1000,700);
    frame.getContentPane().setLayout(null);
    frame.setVisible(true);


    JButton all=new JButton("Set All To");
    frame.getContentPane().add(all);
    all.setBounds(600,450,150,50);
    all.setFont(new Font("Courior", Font.BOLD, 25));
    all.addActionListener(boardListener);

    frame.getContentPane().add(all2);
    all2.setBounds(800,450,50,50);
     all.addActionListener(boardListener);


for ( i = 0; i < 100; i++) {
    JLabel label =new JLabel(forest);    
    label.setIcon(forest);
        listofLabels.add(label);
        a=a+50;
        if(a>549) {
            b=b+50;
            a=50;
        }
        frame.getContentPane().add(label);
        label.setBounds(a, b, 50,50);
        label.setTransferHandler(new TransferHandler("icon"));


            }
}


ActionListener boardListener = new ActionListener (){
    public void actionPerformed(ActionEvent e){
ImageIcon setAll=(ImageIcon) all2.getIcon();

![enter image description here][2]label.setIcon(setAll);



    }
    };;

public static void main(String[]args) {
    new map();
}

}


Solution

  • Why not simply iterate through the array (or ArrayList) of JLabels setting all of the JLabel's Icons to the one selected?

    For example:

    ActionListener boardListener = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
         if (e.getActionCommand().equals("Set All To")) {
            ImageIcon setAll = (ImageIcon) all2.getIcon();
            for (JLabel label : listofLabels) {
               label.setIcon(setAll);
            }
         }
      }
    };