I encountered an issue that I can't seem to resolve while programming the preferences panel in my Java Swing application.
SSCCE:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
/**
* demonstrates the issue at hand
*/
public class Probs extends JFrame {
/**
*
*/
private static final long serialVersionUID = -2320457631507860940L;
JCheckBox one = new JCheckBox("Checkbox One");
JCheckBox two = new JCheckBox("Checkbox Two");
JCheckBox three = new JCheckBox("Checkbox Three");
JCheckBox four = new JCheckBox("Checkbox Four");
final static int BORDER = 10;
final static int WIDTH = 440;
final static int DESC_HEIGHT = 30;
public Probs () {
JTabbedPane options = new JTabbedPane();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//set up the main panel
JPanel pan = new JPanel();
pan.setBorder(BorderFactory.createEmptyBorder(Probs.BORDER, Probs.BORDER, Probs.BORDER, Probs.BORDER));
pan.setLayout(new BoxLayout(pan, BoxLayout.Y_AXIS));
//construct the descriptor subpanel
JPanel desc = new JPanel();
desc.setLayout(new BorderLayout());
desc.add(new CustomLab("Options Title Goes Here"));
JSeparator sep1 = new JSeparator();
desc.add(sep1, BorderLayout.SOUTH);
desc.setPreferredSize(new Dimension(Probs.WIDTH, Probs.DESC_HEIGHT));
desc.setMinimumSize(new Dimension(Probs.WIDTH, Probs.DESC_HEIGHT));
desc.setMaximumSize(new Dimension(Probs.WIDTH, Probs.DESC_HEIGHT));
pan.add(desc);
//basic options
JPanel basic = new JPanel();
basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS));
basic.setBorder(BorderFactory.createTitledBorder("Basic"));
basic.add(one);
basic.add(two);
basic.add(three);
basic.add(four);
basic.setPreferredSize(new Dimension(Probs.WIDTH, basic.getPreferredSize().height));
basic.setMinimumSize(new Dimension(Probs.WIDTH, basic.getPreferredSize().height));
basic.setMaximumSize(new Dimension(Probs.WIDTH, basic.getPreferredSize().height));
pan.add(basic);
options.addTab("Panel One", pan);
add(options);
setSize(500, 500);
setVisible(true);
}
public static void main(String[] args) {
new Probs();
}
}
On my machine (OSX Mountain Lion with Java 7), that produces a result similar to this. I would like to have the Basic panel all the way to the left (and I already tried basic.setAlignmentX(JComponent.LEFT_ALIGNMENT);
to no avail (that line of code had no effect). Furthermore, I already checked out questions such as
to no avail as well.
On an interesting note, if the desc panel is removed (so pan.add(desc);
is commented out), the basic panel then aligns correctly as can be seen .
How to properly left-align the desc and basic jpanels (as well as anything else you see wrong in the code).
Finally, (on a bit of a tangent): is specifying the minimum, maximum, and preferred sizes the proper way to size a JPanel in BoxLayout (it seems very inelegant)?