代码之家  ›  专栏  ›  技术社区  ›  L. Cornelius Dol

文本小部件是否可以在文本中间而不是结尾显示溢出“…”?

  •  0
  • L. Cornelius Dol  · 技术社区  · 17 年前

    我有一个JComboBox,它包含一个MRU列表组合框和一个目录树面板。两者共同构成了我的GUI的左侧面板(MRU位于树面板上方),这是一个JSplitPane,因此左侧面板可以调整大小。

    显示“开始…结束” 而不是“开始……”我的问题就会得到解决。

    Screen Shot http://www.freeimagehosting.net/uploads/da9810ed86.png


    更新

    2 回复  |  直到 17 年前
        1
  •  1
  •   OscarRyz    17 年前

    我认为这是listcell渲染器或类似的东西。

    :)

        2
  •  0
  •   L. Cornelius Dol    13 年前

    代码如下:

    recentDirs.setRenderer(new ComboTextRenderer(recentDirs));
    
    ...
    
    static private class ComboTextRenderer
    extends DefaultListCellRenderer
    implements SwingConstants
    {
    JComponent                          parent;
    int                                 renderWidth;
    
    ComboTextRenderer(JComponent par) {
        super();
    
        parent=par;
        renderWidth=-1;
        }
    
    public void paint(Graphics gc) {
        String                          txt=getText();
    
        int                             len=txt.length();
        int                             wid=getSize().width;
        Insets                          ins=getInsets();
        FontMetrics                     met=gc.getFontMetrics();
    
        if(renderWidth==-1 || wid<parent.getSize().width) { renderWidth=wid; }
        else                                              { wid=renderWidth; }
        wid-=(ins.left+ins.right);
    
        if(met.stringWidth(txt)>wid) {
            String rpl=null;
            for(int xa=0,pfx=Math.min(15,((len/2)-1)),sfx=(pfx+2); pfx>0 && sfx<len; xa++) {
                rpl=(txt.substring(0,pfx)+" ... "+txt.substring(sfx));
                if(met.stringWidth(rpl)<=wid) { break; }
                rpl=null;
                if     ((len-sfx)>15) { sfx++; }
                else if((xa%2)==0   ) { pfx--; }
                else                  { sfx++; }
                }
            if(rpl!=null) { setText(rpl); }
            }
    
        super.paint(gc);
        }
    }