如何在JPanel中建立垂直的TitledBorder(使用javax挥杆)(How to crea

2019-09-18 06:15发布

我试图找出如何创建一个垂直TitledBorderJPanel

我有这样的情况:

我想有“致动器ST ......”垂直放置,所以用户可以读取它。

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

Answer 1:

  • 也许疯狂的想法,但可能与JSeparator太:-)

  • 需要适当LayoutManager ,也许GridBagLayoutJComponent放置而不GBC可以采取PreferrredSizeJComponent ,但并不是resiziable),不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();
            }
        });
    }
}


Answer 2:

正如所示如何使用边框 ,您可以使用空边框和标题边框创建一个合成边框。

附录:作为替代方案,可以使用边框的getMinimumSize()方法来确保标题是可见的。 另见本相关的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;
}


文章来源: How to create vertical TitledBorder in JPanel (javax swing)