How to centre the Buttons in my JFrame?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 16:44:33
Ahmed Laatabi

you can make arrays of JButtons and edit them simply by creating a table of JButtons, and use them with a GridLayout cenetred in Borderlayout.CENTER :

JButton [] buttons = new JButton[n];
for(int i=0;i<n;i++){
    buttons[i] = new JButton("label "+ i);
    buttons[i].set...
    buttons[i].set...
    gridlayout.add(buttons[i]);
}

borderlayout.add(gridlayout, BorderLayout.CENTER);
panel.setLayout(borderlayout);

hope this helps.

Hitham S. AlQadheeb

A way to do it is:

panel.setLayout(new GridLayout(3,10));
panel.setSize(new Dimension(500, 200));
//Add this line
panel.setLocation((frame.getWidth()-panel.getWidth())/2, 0); // 0 is just the Y location
frame.setSize(new Dimension(600, 300));

Look into relative layout to manage all your layouts https://stackoverflow.com/a/5346794/643500

Keep in mind that you want all pieces to layout nicely with each other, otherwise issues can be a pain to deal with. Dahmad Boutfounast's solution is one of those nice ones to have.

And definitely use a list\array to manage all those.

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