Title collapse in TitledBorder

本小妞迷上赌 提交于 2019-12-25 09:26:29

问题


I've a TitledBorder having title larger than the body. Its get cut down and the length sets as per the maximum length of the body.

Suppose I have a label in the body saying TEST and its enclosed by TitledBorder having title TESTING TITLE. In this case the title is cut down and displayed as TESTI

I'm using MigLayout for the body.

Any way to the show the full title irrespective to the content it contains?


回答1:


Borders don't directly participate in size evaluation by the LayoutManager (they are not a JComponent themselves but just decorations around a JComponent).

Hence the only way to ensure that the title in a TitledBorder is completely visible is to enfore a minimum size for the panel it is assigned (or rather for components embedded in that panel).

Minimum size calculation should in this case be based on the current title of your TitledBorder and the Font used by TitledBorder to paint its title.

To be honest, I am not sure, all this work is worth writing.

Based on the exact components comntained inside your TitledBorder, a simpler solution would be to use JTextField.setColumns(n) where n is big enough compared with the title.

Actually a better way would be to avoid TitledBorder altogether, as suggested by Karsten Lentszch from the JGoodies fame, and replace it with a colored JLabel and a horizontal JSeparator, that would fully participate in the layout and hence be used for size computation.




回答2:


I have found that adding a Horizontal Strut of an appropriate width will force the panel to resize so that it shows the entire title:

    myPanel.add(Box.createHorizontalStrut(desiredWidth));

I'm sure there is probably a way to dynamically find the desired width at runtime, but I just do it the lazy way: set it to a width that covers the size of my TitledBorder title text.




回答3:


This works well for me:

 final String myPanelTitle = UIManager.getString("myPanel_title");
 final Border myPanelBorder = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GREEN), myPanelTitle);
 JPanel myPanel = new JPanel(){
      @Override
      public Dimension getPreferredSize(){
           Dimension d = super.getPreferredSize();
           int insets = 2 * (myPanelBorder.getBorderInsets(this).left + myPanelBorder.getBorderInsets(this).right);
           double minWidth = this.getFontMetrics(this.getFont()).stringWidth(myPanelTitle) + insets;
           if(d.getWidth() > minWidth)
                 minWidth = d.getWidth();
           return new Dimension((int)minWidth, d.height);
       }
 };
 myPanel.setBorder(myPanelBorder);


来源:https://stackoverflow.com/questions/5744611/title-collapse-in-titledborder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!