1

我有一个带有 TitledBorder 的 JPanel,但面板的内容比边框中的标题窄,并且标题被截断。我正在为 JPanel 使用 BoxLayout,如此处所述,它注意手动设置宽度。我尝试根据 TitledBorder getMinimumSize() 函数及其组件的宽度设置面板的最小、最大和首选宽度,但都不起作用。唯一有效的是使用盒子填充物,但这会引入不希望的压痕。

不管它包含什么内容,有什么方法可以显示完整的标题?

this.jpCases.setLayout(new javax.swing.BoxLayout(this.jpCases, javax.swing.BoxLayout.LINE_AXIS));
        List<Category> categories = db.getCategories();
        for (Category cat : categories) {
            JPanel jp = new JPanel();
            TitledBorder tb = BorderFactory.createTitledBorder(cat.getDescription());

            jp.setBorder(tb);
            jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
            jp.setAlignmentY(Component.TOP_ALIGNMENT);
            jp.setAlignmentX(Component.LEFT_ALIGNMENT);

            List<Case> cases = db.getCasesByCategoryId(cat.getId());
            for (Case c : cases) {
                JRadioButton jrbCase = new JRadioButton();
                jrbCase.setText(c.getDescription());
                jrbCase.setToolTipText(c.getText());
                jrbCase.setMaximumSize(tb.getMinimumSize(jp));
                bgCases.add(jrbCase);
                jp.add(jrbCase);
            }
        //jp.add(new Box.Filler(tb.getMinimumSize(jp), tb.getMinimumSize(jp), tb.getMinimumSize(jp)));
            this.jpCases.add(jp);
    }
4

3 回答 3

2

如何计算所需的宽度:

       JRadioButton jrb = new JRadioButton();
       int width = (int) SwingUtilities2.getFontMetrics( jrb, jrb.getFont() ).getStringBounds( cat.getDescription(), null ).getWidth();
       for (Case c : cases) {
            JRadioButton jrbCase = new JRadioButton();
            jrbCase.setText(c.getDescription());
            jrbCase.setToolTipText(c.getText());
            jrbCase.setPreferredSize( new Dimension( width, jrbCase.getPreferredSize().height ) );
            bgCases.add(jrbCase);
            jp.add(jrbCase);
        }
于 2011-06-20T07:53:37.727 回答
1

这对我很有效:

 JPanel aPanel = new JPanel(){
      @Override
      public Dimension getPreferredSize(){
           Dimension d = super.getPreferredSize();
           Border b = this.getBorder();
           if(b == null) return d;
           if(!(b instanceof TitledBorder)) return d;
           TitledBorder tb = (TitledBorder)b;
           if(tb.getTitle() == null) return d;
           int insets = 2 * (tb.getBorderInsets(this).left + tb.getBorderInsets(this).right);
           double minWidth = this.getFontMetrics(tb.getTitleFont()).stringWidth(tb.getTitle()) + insets;
           if(d.getWidth() > minWidth) return d;
           return new Dimension((int)minWidth, d.height);
      }
 };
于 2016-10-03T01:37:49.160 回答
0

我通过在面板的顶部(或底部)添加标签 (BoxLayout.Y_AXIS) 来“解决”它。标签仅包含与标题相同(或更大)宽度的空格。(使与标题具有相同文本的标签不可见并不能解决它。)

于 2013-07-02T22:06:20.113 回答