I want to make a Firefox like Option Dialog in Java with Swing.
I tried now to align all my elements on the north of the Window. I made it with the first element, but the next Elements are filling the room vertically and are not aligned.
For this i’m using the GridBagLayout.
Here is the code:
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class Background {
private Border headBorder = BorderFactory.createEmptyBorder(15, 8, 10, 8);
private GridBagConstraints headPaneConstrain;
private JPanel headPane;
public Background() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame dialog = new JFrame();
//headPane
dialog.add(headPane());
//2 elements
createSetting("test");
createSetting("test2");
//dialog settings
dialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dialog.setSize(500,500);
dialog.setVisible(true);
}
});
}
private JPanel createSetting(String name) {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(name));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
headPane.add(panel,headPaneConstrain);
return panel;
}
private JPanel headPane(){
//Constrain
headPaneConstrain = new GridBagConstraints();
headPaneConstrain.fill = GridBagConstraints.HORIZONTAL;
headPaneConstrain.anchor = GridBagConstraints.NORTH;
headPaneConstrain.weightx = 1.0;
headPaneConstrain.weighty = 1.0;
headPaneConstrain.gridx=0;
//HeadPane
headPane = new JPanel();
headPane.setBorder(headBorder);
headPane.setLayout(new GridBagLayout());
return headPane;
}
public static void main(String[] args) {
new Background();
}
}
Thanks for help
If you don’t want your ” inner” panels to grow vertically, then why do you set
weigthyto 1.0? You should set it to 0.0 instead (at least for all panels that should not grow vertically).Besides, please pay attention that using borders will have an impact on alignments of components between 2 panels.
A better way to show different “sections” in a form is to use only one panel for the whole form and separate sections with a
Jlabelfollowed by a horizontalJSeparator.For this kind of form, I would use
DesignGridLayout(rather thanGridBagLayoutwhich is too much of a PITA to get what you want…), but I’m biased here.