Search code examples
javaswingjlabel

Changing the name of JLabel in java dynamically


I have a Swing program in which, I have to change the JLabel's name dynamically in action performed block.


Solution

  • The JLabel is an object, the name you assign that data type will make the mapping between the memory allocated in the Heap and the object self, if you want to change the name, then re allocate the object by creating a new one, with a new variable name.

    you can work with collections

    HashMap<String, JLabel> aWeirdLabelMap = new HashMap<String,JLabel>();
    aWeirdLabelMap.put("anAlias0x00", new JLabel("myLabel1"));
    aWeirdLabelMap.get("anAlias0x00");
    

    another way:

    List<JLabel> jlabelList = new ArrayList<JLabel>();
            JLabel buf = null;
            for (int i = 0; i < 5; i++) {
                buf = new JLabel("label_" + i);
                buf.setName(Integer.toString(i));
                jlabelList.add(buf);
            }
    
            //later iterate or loop to find it
            JLabel c = null;
            for (JLabel jlabelList1 : jlabelList) {
                if (jlabelList1.getName().equalsIgnoreCase(Integer.toString(1))) {
                    c = jlabelList1;
                    System.out.println("JlabelFound -->" + c.getName() + c.getText());
                }
            }