How to move JButtons and JLabels position in a JPanel, JFrame

此生再无相见时 提交于 2019-12-06 14:57:30

Instead of using a FlowLayout, which rearranges items automatically based on their sizes and the window size, you can use a BorderLayout or GridLayout. A BorderLayout basically splits the window into 5 areas, each border is a separate area identified with a cardinal direction (north, east, etc.), and the center is it's own area as well. A GridLayout allows you to specify if you want a particular number of rows/columns, while letting the other expand as necessary (n elements into 2 columns, for example).

From the look of your photoshopped desired outcome, you can use a BorderLayout for the main frame, with the buttons in the north, the number/results in the center, and the table in the south. Also remember that you can put a panel in a layout area, with that panel having its own layout, such as a GridLayout for the buttons in the north, or even better, for the table in the south. Hope that helps!

Some code to assist you:

JFrame frame = new JFrame("The Lottery");
JPanel mainPanel = new JPanel(new BorderLayout());

JPanel northPanel = new JPanel();
JButton play = new JButton("Play");
JButton exit = new JButton("Exit");
northPanel.add(play);
northPanel.add(exit);
mainPanel.add(northPanel, BorderLayout.NORTH);

What I'm looking to achieve is for the buttons position to never move, and to put the text under the buttons.

JPanel by default use FlowLayout that adds the component one after another. You can use multiple JPanel as well and add in another ``JPanel`.

If you want to display text below the button then use BorderLayout or GridBagLayout.

It's worth reading Swing Tutorial on How to Use Various Layout Managers

Sample code:

JPanel topPanel = new JPanel();
topPanel.add(new JButton("Play"));
topPanel.add(new JButton("Exit"));

JPanel panel = new JPanel(new BorderLayout());
panel.add(topPanel, BorderLayout.NORTH);
panel.add(new JLabel("Hello", JLabel.CENTER));

snapshot:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!