0

I am trying to create some easier ways for me to create a GUI, and I'm trying to create a method with parameters that I will call in the method. I'm quite new to Swing (and Java).

This is what I am TRYING to do.

    public static void createLabel(String labelName, String labelText) {
        
        JLabel labelName = new JLabel();
        labelName.setText(labelText);
        mainFrame.add(labelName);

    }

This is what I'm trying to do but to be honest, I don't even know if it is possible!

Thanks for reading!

Austin
  • 9
  • 1
  • 1
    So, you want to create a factory method then. Personally, though, I'd have the method return an instance of `JLabel` – MadProgrammer Jun 09 '21 at 03:59
  • 1
    Java does not have dynamic variable names. – NomadMaker Jun 09 '21 at 04:14
  • All _Swing_ components, like [JLabel](https://docs.oracle.com/javase/8/docs/api/javax/swing/JLabel.html), extend class `java.awt.Component` and that class has methods [getName](https://docs.oracle.com/javase/8/docs/api/java/awt/Component.html#getName--) and `setName`. Perhaps that can help you? Alternatively, class `JComponent` has methods [getClientProperty](https://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#getClientProperty-java.lang.Object-) and `putClientProperty`. Perhaps that can help you? – Abra Jun 09 '21 at 05:32

1 Answers1

0

Looks like you are trying to dynamically define a variable. That is not possible in plain Java.

See: Assigning variables with dynamic names in Java, and How to create variables dynamically in Java?.

If you cannot commit to a variable name at compile-time, an alternative is putting your objects in a collection. For example, a Map tracks key-value pairs, where knowing a key can give you its paired value object.

Map< String , Label > labelsMap = new HashMap<>() ;
labelsMap.put( "alice" , new JLabel( "Alice" ) ) ;
labelsMap.put( "bob" , new JLabel( "Bob" ) ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154