I am trying to create a UI layout using BoxLayout. It is fairly simple: there's a custom component on the right and some random input controls on the left. Trouble is that the component can be quite big, and the LINE_AXIS BoxLayout on the content pane wants to make the controls on the left completely fill the space created by the height of the component on the right. This code should demonstrate:
import javax.swing.BoxLayout;
import javax.swing.Box;
import javax.swing.JPanel;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import java.awt.Graphics;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
// Java view mockup.
// This is so the Swing documentation applies directly to any layout problems.
public class View extends JFrame {
private JPanel control;
private JComponent display;
public View() {
super("tortoise");
JPanel content = new JPanel();
//content.setLayout(new BoxLayout(content, BoxLayout.LINE_AXIS));
control = new Control();
display = new Display();
content.add(control);
content.add(display);
content.setOpaque(true);
setContentPane(content);
pack();
setVisible(true);
}
public static void main(String[] args) {
View v = new View();
}
class Control extends JPanel {
public Control() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(new LabelledSpinner("Parameter 1:"));
add(Box.createVerticalGlue());
add(new LabelledSpinner("Parameter 2:"));
add(Box.createVerticalGlue());
add(new LabelledSpinner("Parameter 3:"));
add(Box.createVerticalGlue());
add(new LabelledSpinner("Parameter 4:"));
}
class LabelledSpinner extends JPanel {
private JLabel label;
private JSpinner spinner;
public LabelledSpinner(String lbl) {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
label = new JLabel(lbl);
spinner = new JSpinner();
add(label);
add(spinner);
}
}
}
class Display extends JComponent {
protected void paintComponent(Graphics g) {
// do nothing!
}
public Dimension getPreferredSize() {
Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
return new Dimension(
(int) (scr.getWidth() / 2.0), (int) (scr.getHeight() / 2.0)
);
}
}
}
Vertical glue eases the problem a little bit but the spinners are still huge. I have tried many different alignments for components and none seem to fix it. The behaviour I want is simple, and is in fact the exact behaviour created by using a FlowLayout in the content pane instead. However, I was hoping out of sheer bloodymindedness to lay out all my components with BoxLayout, since the Java tutorial says "You might think of [BoxLayout] as a full-featured version of FlowLayout." Is this actually possible with BoxLayout?