2011-06-20 51 views
1

我有一個帶有TitledBorder的JPanel,但面板的內容比邊框中的標題窄,標題被截斷。 我正在使用BoxLayout作爲here所示的JPanel,注意寬度的手動設置。我試圖根據TitledBorder getMinimumSize()函數以及其組件的寬度設置面板的最小,最大和首選寬度,但都不起作用。唯一有效的工作是使用盒裝填料,但引入了不希望的縮進。標題截斷JPanel TitledBorder - Java swing

任何方式顯示完整的標題,而不管它包含的內容?

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); 
    } 
+3

爲了更好地幫助越早,張貼[SSCCE(HTTP:// pscode.org/sscce.html)。 –

回答

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); 
     } 
+1

上述代碼不能按原樣運行。這似乎與BoxLayout,設置大小這種方式沒有任何影響。但是,如果在將組件添加到JPanel之後添加horizo​​ntalGlue,則它完美地工作! – vkolias

0

我通過添加標籤(BoxLayout.Y_AXIS)到面板的頂部(或底部)「解決」它。該標籤僅包含導致標題寬度相同(或更大)的空格。 (有非常相同的文字作爲標題無形不能解決它使標籤。)

0

這很適合我:

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