What are the benefits of using an existing layout manager as opposed writing a listener that handles resizing functions? For instance, I needed to arrange buttons in a grid and center the grid:
int h = component.getHeight() / 11;
int w = component.getWidth() / 9;
int offsetX = w;
int offsetY = h;
int x = (2 * column) * w - offsetX;
int y = (2 * row) * h - offsetY;
setBounds(x, y, w, h);
Instead of fumbling around with a layout manager I wrote this small bit of code that is activated for the buttons whe开发者_JAVA百科never the JPanel is resized. If I were to use a layout manager, it would be more cumbersome to write the code to arrange everything and if I were to say add a component to the JPanel, things would get even more complex as opposed to simply adding a few additions or subtractions.
So given this, would there be any benefits to using a layout manager in a situation as this or would a few customized lines be easier to use and maintain?
Your code is basically mimicking a GridLayout
.
setLayout(new GridLayout(11, 9));
// add all the components
...
// Profit
To center it:
JPanel outerPanel = new JPanel(new BorderLayout());
JPanel gridPanel = new JPanel(new GridLayout());
outerPanel.add(gridPanel, BorderLayout.CENTER);
It's possible that for something so simple, writing your own code is easy enough. But what will happen when you find out you need to add two new buttons and a text area? I think learning to use the Layout Managers is a good investment of your time, since the knowledge will allow you to scale your GUI's complexity easily. (No pun intended ;)
Cool. Now try to write the same 128 times (for each control on each screen). And it is not the end of the game. Now try to change graphic design your application, i.e. rewrite this code 128 times again. Enjoy!
精彩评论