如何在JPanel中创建垂直TitledBorder(javax swing)

时间:2012-06-18 21:51:42

标签: java swing jpanel titled-border

我正在尝试弄清楚如何在TitledBorder中创建垂直JPanel

我遇到了这种情况:

image http://img525.imageshack.us/img525/2225/testyid.png

我希望将“Actuators st ...”垂直放置,以便用户可以阅读。

有没有办法,或者我应该实施自己的自定义JPanel& TitledBorder

2 个答案:

答案 0 :(得分:2)

How to Use Borders所示,您可以使用空边框和标题边框创建复合边框。

附录:作为替代方案,您可以使用边框的getMinimumSize()方法来确保标题可见。另请参阅此相关Q&A

enter image description here

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;
}

答案 1 :(得分:2)

  • 也许是疯狂的想法,但也可以使用JSeparator: - )

  • 要求正确LayoutManager,可能GridBagLayoutJComponent没有GBC,可以从PreferrredSize获取JComponent,但不是{#1}} 39; t resiziable),而不是GridLayout

enter image description here

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();
            }
        });
    }
}