Value CENTER is not a member of object javax.swing.JLabel

I am translating code from Java to Scala and came across this:

JLabel l = new JLabel(label, JLabel.CENTER);

so I tried:

    val l = new JLabel(trueLabel, JLabel.CENTER)

and the compiler tells me that CENTER is not a member. But looking at the source I have:

public class JLabel extends JComponent implements SwingConstants, Accessible
{
  ...
}

and

public interface SwingConstants {

        /**
         * The central position in an area. Used for
         * both compass-direction constants (NORTH, etc.)
         * and box-orientation constants (TOP, etc.).
         */
        public static final int CENTER  = 0;

Do I have to do anything from the Scala side to access this member?
I am using Scala 3 (Dotty)

TIA

1 Like

SwingConstants.CENTER …?

Messed up a direct reply. Trying again…

I am using that, however I am assuming the implements should work. Note that if it does not work, this means we have to manually hunt down the definitions. This does not seem to be practical. Maybe I am missing something obvious?

Thank you.

In Java, interface fields are static, so they most naturally map to members in the companion object of a trait in Scala. While you can access static members via an object reference in Java, the (unmaintained?) code conventions state: “Avoid using an object to access a class (static) variable or method. Use a class name instead.” (§10.2)

So while I don’t know the actual mechanics at play in Java interop, I’m not terribly surprised that inheritance doesn’t seem to apply to Java interface fields when viewed from the Scala side.

1 Like

In Java, static members like CENTER are inherited just like non-static members.

When referring from Scala to a static member from Java it is understood to be a member of the companion object and is not inherited.

So, yes, you need to find out where it is actually defined.

1 Like