danelliott
danelliott

Reputation: 180

How can I access a swing component added to a JPanel that has not been declared?

If I add a component (say a JLabel) to a JPanel without declaring it, is there a way I can access the JLabel after its instantiation? I'm trying to set the alignment of the component but can't access the setAlignmentX() method even through getComponent().

testPanel.add(new JLabel("test label"));
testPanel.getComponent(0).setAlignmentX(Component.CENTER_ALIGNMENT);

I've tried getComponent() but the setAlignmentX() method cannot be resolved, leading me to believe that the getComponent() method isn't returning the JLabel correctly, possibly because I never formally declared it. I don't have any other components added to the JPanel. I know I could always declare the JLabel prior to adding it to the JPanel, but I'd rather just add the new JLabel("test label") rather than declaring one prior to adding it.

Upvotes: 1

Views: 85

Answers (1)

Zircon
Zircon

Reputation: 4707

It would probably be considered best practice to declare the JLabel first as you've mentioned, but to answer your question...

The method getComponent(int) returns a java.awt.Component, not a JComponent (nor JLabel). Component has no such method setAlignmentX (it only has a getter).

Supposing you're sure the component you're getting is a JLabel, you'd have to cast it:

((JLabel)testPanel.getComponent(0)).setAlignmentX(Component.CENTER_ALIGNMENT);

You might see that universalizing this necessary cast everywhere would be less maintainable than just declaring the JLabel first.

Upvotes: 1

Related Questions