JButton orientation within a JPanel

2019-07-25 18:00发布

问题:

I am designing a GUI for an image editor in which I have multiple buttons which apply different effects to the selected image. Currently I have the Display button in the top center of the window, the Load button in the bottom center of the window, and I want the effect buttons stacked on the left side of the window. Here is the image of my GUI, with the ButtonPanel JPanel in red, the FileChooser JPanel in green, and the ImageDisplay JPanel in blue:

As you can see, the buttons in the ButtonPanel are stacking horizontally instead of vertically. I would like them to stack vertically. Thank you for the help.

回答1:

the buttons in the ButtonPanel are stacking horizontally instead of vertically. I would like them to stack vertically.

The default layout for a JPanel is a FlowLayout which displays all components horizontally.

Use a different Layout Manager. Maybe a GridLayout. With a GridLayout you can display components vertically if you set the constructor parameters properly.

Read the section from the Swing tutorial on Layout Managers for more information and working examples.



回答2:

the buttons in the ButtonPanel are stacking horizontally instead of vertically. I would like them to stack vertically.

You can try with BoxLayout as well that allows multiple components to be laid out either vertically or horizontally.

Please have a look at How to Use BoxLayout where you will find the sample code as well.



回答3:

Another option is to use a JToolBar (kind of like in PhotoShop) where you can change the orientation or float the tool bar around. See more at How to Use Tool bars