Question

I am trying to create a space between an ImageIcon and a JButton, which are placed in the same JPanel side by side.

This is what I have so far:

allPanels.add(middlePanel);
middlePanel.add(grassPanel);
grassPanel.setLayout(new BoxLayout(grassPanel, BoxLayout.LINE_AXIS)); 
grassPanel.add(new JLabel(new ImageIcon("grass.jpg")));
buyGrass = new JButton("Buy Food");
grassPanel.add(buyGrass);

Is there anyway to separate the image and the button, so that the image is more to the left and the button is more to the right?

Was it helpful?

Solution

Have a look at Box.createHorizontalStrut(int). This will add an empty area, e. g.:

grassPanel.add(new JLabel(...));
grassPanel.add(Box.createHorizontalStrut(10));
grassPanel.add(buyGrass);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top