2

我试图弄清楚如何TitledBorderJPanel.

我有这种情况:

图片

我想垂直放置“Actuators st ...”,以便用户可以阅读它。

有没有办法做到这一点,或者我应该实现自己定制的JPanel& TitledBorder

4

2 回答 2

2
  • 也许是疯狂的想法,但也有可能JSeparator:-)

  • 需要适当的LayoutManager,也许GridBagLayoutJComponent放置没有GBC可以PreferrredSize取自JComponent,但不可调整大小),不是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();
            }
        });
    }
}
于 2012-06-18T22:56:56.183 回答
2

如何使用边框中所示,您可以使用空边框和带标题的边框创建复合边框。

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

在此处输入图像描述

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;
}
于 2012-06-18T22:40:02.907 回答