how to use the layout managers in swing java - java

I'm new to layout managers like Flow, borders, ...
I mostly use setBounds() to set the position of my components.
I read on an article that using setBounds is not an good practice and it's better to use some layout.
Which are the best and most used layouts?
How to position a button using layout managers; instead of doing setbounds(10,10,100,30)?

look here: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
Basically you should forget about coordinates. Look at your dialogs at a higher level of design. Questions you should ask yourself.
1) Is there a "main" area with smaller surrounding areas in your design. If so use a BorderLayout.
2) Is there equal grid like areas in your design, If so use a GridLayout.
3) If you need a top-down, or left-right layout, consider a BoxLayout
4) If you want to show a complex form, probably use a FormLayout from jgoodies.
But you have to look at things from a high level. There may be subsections in any one top level section of your dialog. If that is the case, then you need to put a JPanel in that section, and then use a sub layout in that JPanel. Use the above questions over again for that panel.

Besides "standard" Swing layouts (part of the JDK), there are many third-party (mostly open source) LayoutManagers that often are much better than Swing ones.
For a comparison of many LayoutManagers on a real example (with code), check out this link, although a bit old, it still shows the various features and ease of use of predominant LayoutManagers nowadays.
In general, I would advise DesignGridLayout which, although quite powerful, is very easy to use (you don't need a GUI designer to use and it's easy to maintain layout code of existing panels); it just takes one hour to understand it.
Also, MigLayout is viewed as the most flexible one (might be useful if you need very complex layouts), but it takes more time to get used to it, and sometimes you have to use "tricks"to make it work as you want.

..which is the best and most used layout (?)
Nested layouts. Use whatever layout works best for different groups of GUI components, then put them in panels inside other panels (with other layouts). See this Nested Layout Example for a demo. of combining layouts.
As to which best individual layouts to use, do the tutorial linked by MBFG to get a feel for what each can achieve, their strengths & weaknesses.
I will commonly use nested combinations of BorderLayout, GridLayout & FlowLayout, with an occasional GridBagLayout.

Related

JPanel and Java layout managers

Having read over the internet about JPanel for a while I feel I still need clarification after reading it. My questions:
What is JPanel mostly used for?
Which layout manager is most flexible to use?
How do you position components at certain areas using layout managers?
I find it really difficult to position components at certain areas within the container using a layout manager.
What layout manager do you recommend I use or do you have to use a mixture of different ones?
My first question is what is JPanel mostly used for.
You already know that. You add components to the panel.
My second question is which layout manager is most flexible to use
The more flexible that layout manager, the more complicated the layout manager is to use. So the trick is design your GUI logically and then use multiple panels with different layout manager to achieve your desire effect.
Each layout manager has its own strengths and weaknesses.
I find it really difficult to position components at certain areas within the container using a layout manager.
That is old thinking. You should not be trying to position components specifically. You position components generally and let the layout manager adjust as the size of the frame is changed by the user.
Maybe you want components centered, or in a grid. There are different layout managers to achieve your task. We can't give specific advice. If you have a specific problem then as a specific question and post your code that shows what you have tried.
But first, read the Swing tutorial on Layout Manager and download the example code play with the code to understand how each works. You learn by trying.
What layout manager do you recommend I use or do you have to use a mixture of different ones.
It depends on the GUI. I'd typically use a combination of layout managers for anything but the most trivial user interfaces. On the other hand, some like to try and use a more complex layout for those same GUIs, using layouts like:
GridBagLayout - older, but quite versatile.
GroupLayout - newer, more powerful, and provides better ability to align elements that are not next to each other, but considered so difficult to hand write that most use a GUI designer that will produce code that will not be portable to the next GUI designer or IDE.
A third party layout manager like MigLayout or FormLayout
JPanel can be used:
As a container for other components
Base for a custom widget
Drawing area
MigLayout is hands down the most flexible layout manager.
There are many layout managers in Swing, but in my opinion
only three are up to the job:
MigLayout
GroupLayout
FormLayout
Since MigLayout is an (greatly) improved FormLayout, I usually
recommend the first two managers.
Using a mixture of various managers is a poor practice. It is a way
of overcoming the simplicity of basic layout managers. One should choose a good layout manager and not to tangle with multiple layout managers. Most layouts can be easily done with MigLayout and GroupLayout.

How to choose gaps between components suitable for current Look and Feel?

When creating Swing GUI's, how can I best choose the horizontal and vertical gaps to be used to separate components? Something like asked here Windows Layout Look and Feel, but platform independent.
Generally I simply used 5 pixels for everything, that looked reasonable with the Windows Classic theme, but looks somewhat odd when running under Windows 8, especially when there are multiple nested container components (e.g. Dialog -> TabbedPane -> ScrollPane).
I have looked at UIDefaults, but there doesn't really seems to be any hints about component spacing there (I was hoping to find at least a few values that could be used as hints, but LayoutManagers seem to generally use hardcoded deafults, e.g. FlowLayout uses a hardcoded 5 pixel spacing).
What approaches can I take to make my layouts more look and feel aware (I am generally using the System Look and Feel) ?
If you want a layout of components that change a bit to fit your user's platform, then perhaps just use the user's system look and feel with:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Edit to provide solution for specifying more specific gaps.
To specify margin and padding between components you can try using a box layout. You might not need to use a box layout throughout the entire Swing code you have either, perhaps have a utility function you use right before you add a component that accepts a Swing component, and a left right top and bottom margin/padding. This function would then return you a JPanel with a box layout with the margin/padding passed, along with containing one component, the one you passed in.

Can SpringLayout do all the job

I would like to ask if SpringLayout can do anything like absolute position because I think absolute position have problem when I maximize the frame and what do I have to use if I need to set JMenu and JToolBar and JTextField and JTable all in one line in order?
I tried to use Borderlayout but it give me very big JTextField. I tried Gridlayout it give also big JTextField I need it big but not as big as it shows up.
can SpringLayout do all the job
No. It is neither designed, nor intended to do 'all the job'.
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
For absolute positioning, don't use a layout manager at all.
However, that's not really recommended. Usually you should use a layout that would scale.
See also this thread for more discussion.
i found note writing by java says
Note: This lesson covers writing layout code by hand, which can be
challenging. If you are not interested in learning all the details of
layout management, you might prefer to use the GroupLayout layout
manager combined with a builder tool to lay out your GUI. One such
builder tool is the NetBeans IDE. Otherwise, if you want to code by
hand and do not want to use GroupLayout, then GridBagLayout is
recommended as the next most flexible and powerful layout manager

Is there a LayoutManager in the Java API that would allow me to do like this?

I'm programming this level creator for a game me and a few of my friends are doing but as of right now the GUI is using a null layout, which I don't want to. It works fine for now, but I'm still against it and I know everyone else also encourages you to ALWAYS use a LayoutManager. I'm not really willing to compromise the design as it is right now, so I pretty much want to know if there's a LayoutManager that allows me to create a GUI that looks like this:
IT HAS TO BE IN THE STANDARD JAVA API! :)
This looks like a good job for a BorderLayout. Put the buttons inside a nested container as the NORTH element. Add the JScrollPane as the CENTER component. The grid itself looks like it is a good candidate for a GridBagLayout or perhaps a GridLayout.
Short answer, yes: GridBagLayout. But that'll be a pain to work out and debug.
Long answer: It looks to me like you could do this best with a BorderLayout, a JPanel for the JButtons, and a JTable with custom TableCellRenderers and TableCellEditors.
Check the excellent documentation available for Java by Sun itself:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Can you spot the GridLayout and GridBagLayout? If you put it into a scrollable container, that should do the trick.
Use GroupLayout for the overall panel and a custom paint method for the map.
I don't think many people here would recommend GroupLayout because it's more complicated than the other layout managers. I like it because it produces great scalable results, so I invested the time in understanding it. Now, I hardly use anything else - especially for user interaction panels with buttons and text fields.
For the map, though, I would create a custom MapPanel and overwrite paintComponent(). Sure you have to write your own custom scrolling algorithm, but I think that's a small benefit for not having to deal with scroll bars. You could make it so someone could just drag the mouse around and move the map. Use the mouse wheel to zoom, and make the interface very intuituve. If you want to paint scrollbars, you can do that too.
I've built several interfaces using models like this. I've built several maps for games using this model, as well as a financial market charting package. It makes it very easy to add custom functionality to do some great things that would be a nightmare to try to do in a JTable.

Why is it frowned upon to use a null layout in Swing?

Recently, I started creating a program for the company I work for. Just as background info, I'm still a student and a beginner programmer, so my solution is probably not recommended and I didn't know how to do it otherwise, but it works and I'm not going to be judged for it because it's a student job totally unrelated to programming.
The thing about the program is, it's going to be run on multiple different computer with different screen sizes and resolutions (800x600 and up). To make sure it takes as much of the screen as possible without losing any part of the program, I set the layout to null and hard-coded everything using relative values.
The program is kiosk-style and I first get the screen size values and go from there (for example, off the top of my head, the left-side menu takes an eighth of the screen, the top bar 2%, etc.). I also use font metrics to make sure the components are sized correctly and that everything gets displayed nicely.
My question is: why is it so frowned upon to make the layout null instead of using the layout managers? (I was told on some forums that this is a horrible way of doing things) I know how the layout manager works and know how to use the different layouts, but for the requirements of this program (multiple different resolutions, custom button shapes and placements, text changing on the components when you change language, etc.), I couldn't see myself using the layout managers to do it all.
How do you more experienced programmers use the layout managers in a situation like this? And what do you do when you want a button to be somewhere specific and other components somewhere else specific that don't really match any of the predefined layouts?
If you layer the layout managers correctly the screen will re-flow to different sizes for you, the idea is to use a single set of layout managers on ALL screen sizes.
If you use null you will have to do each screen size yourself. Not only that but if the app can be windowed you have to support every possible size they might scroll to.
That's kind of difficult to do, but the layout mangers are designed to do just that.
There are some common tricks. BorderLayout is a great layout to start with. Sometimes you might use it at multiple levels--often with just 2 or 3 components in it. That's because it's really good at giving all but one area the minimum required area and giving everything else to the CENTER.
FlowLayout can be useful but it's tricky if your components are different sizes.
I wouldn't try GridBagLayout unless you are planning to write code to feed your layout manager (an excellent solution at that!).
I also wouldn't use GUI builders, they don't know the overall way you want to reflow your layout.
In a nutshell: because all the work that you explain above is done (or at least: should be done) by the layout manager.
More often than not, when a null layout is used, it also implies that all positions and sizes are hardcoded to a single value, so no flexibility at all is given. This means that changes in window size, language, font size, display density or any other related parameter have no effect on the layout and you get the usual ugly effects: empty parts of the window; tiny, unresizable lists; buttons with their labels cut off; ...
It sounds like the work you do should really be done by the Layout Manager. Either find one that does that (my personal suggestion would be MiGLayout, which does a lot and is easy to use) or write your own.
You are practically using a layout - your own, with all your sophisticated calculations of positions.
You can move these logic to a custom layout manager class to pacify the critics.
hmmm trick should be by mixing LayoutMangers and by usage of numbers of nested JPanels that each could have diferrent Layout or not, really depends of number of JComponents, that allows you to create GUI that looks like as layed by using AbsoluteLayout but with same look/output to the GUI for every screen resolutions and ratio (4:3, 16:9, 16:10)

Categories