I'm trying to figure out how to create a vertical TitledBorder
in a JPanel
.
I've got this situation:
image http://img525.imageshack.us/img525/2225/testyid.png
I'd like to have "Actuators st..." placed vertically, so user can read it.
Is there a way to do it, or should I implement my own customized JPanel
& TitledBorder
?
maybe crazy idea but is possible with JSeparator
too :-)
required proper LayoutManager
, maybe GridBagLayout
(JComponent
placed without GBC
can take PreferrredSize
from JComponent
, but isn't resiziable), not GridLayout
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingUtilities;
public class NestedLayout {
private JFrame frame = new JFrame();
private JPanel leftPanel = new JPanel();
private JSeparator sep = new JSeparator();
private JLabel label = new JLabel("<html> L<br>a<br>b<br>e<br>l<br></html>");
public NestedLayout() {
label.setOpaque(true);
sep.setOrientation(JSeparator.VERTICAL);
sep.setLayout(new GridLayout(3, 1));
sep.add(new JLabel());
sep.add(label);
sep.add(new JLabel());
leftPanel.setLayout(new BorderLayout());
leftPanel.setBorder(BorderFactory.createEmptyBorder(
10, //top
10, //left
10, //bottom
10)); //right
leftPanel.add(sep, BorderLayout.CENTER);
leftPanel.setPreferredSize(new Dimension(40, 220));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(leftPanel, BorderLayout.WEST);
//frame.add(label);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
NestedLayout nestedLayout = new NestedLayout();
}
});
}
}
As shown in How to Use Borders, you can create a compound border using an empty border and a titled border.
Addendum: As an alternative, you can use the border's getMinimumSize()
method to ensure that the title is visible. See also this related Q&A.
f.add(createPanel("Actuator status"), BorderLayout.WEST);
f.add(createPanel("Indicator result"), BorderLayout.EAST);
...
private Box createPanel(String s) {
Box box = new Box(BoxLayout.Y_AXIS);
TitledBorder title = BorderFactory.createTitledBorder(null, s,
TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION);
box.setBorder(title);
for (int i = 0; i < 6; i++) {
JButton b = new JButton(null, UIManager.getIcon("html.pendingImage"));
b.setAlignmentX(JButton.CENTER_ALIGNMENT);
box.add(b);
}
box.validate();
Dimension db = box.getPreferredSize();
int max = Math.max(title.getMinimumSize(box).width, db.width);
box.setPreferredSize(new Dimension(max, db.height));
return box;
}