Question

What is the best way to add a JLabel[][] to Box?

I am making an Image[][] and I want to add each element of this image array to JLabel[][]. I can do this. But I want to add JLabel[][] to Box. I use Box to hold all my java components such as JPanel, JButton etc. But when I try to add JLabel[][] to the Box, it doesn't allow it. Would it be safe to use JPanel[][] or some other component?

anyBox.add(JLabel[][]);
Was it helpful?

Solution

You're trying add an array of object into a method that does not allow this, and by trying this, you're breaking some basic Java rules -- the main one being that you're making up methods that don't exist. Instead you have to use the methods that are available to you and pass in the types of objects allowed. A container such as a JPanel will allow you to add other components into it, and so this is what you should do. Give it a decent layout, perhaps a GridLayout, and use a for loop to add your components into it, one at a time.

Note, that if you're trying to add a grid of components, then don't use a Box object as it forces you to use a BoxLayout, which is not appropriate to your needs. Use a JPanel with a GridLayout or GridBagLayout or MigLayout or any layout that more readily displays a grid of components.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top