• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JComboBoxのアイテム文字列を左側からクリップ
#navi(../)
*JComboBoxのアイテム文字列を左側からクリップ [#ia7b0026]
Posted by [[terai]] at 2007-06-18

#contents

**概要 [#x435c009]
JComboBoxのアイテム文字列がコンポーネントより長い場合、これを左側からクリップします。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#x51d3784]
#code{{
final JButton arrowButton = getArrowButton(combo02);
combo02.setRenderer(new DefaultListCellRenderer() {
  public Component getListCellRendererComponent(JList list, Object value, int index,
                          boolean isSelected, boolean cellHasFocus) {
    super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
    Insets insets = getInsets();
    int availableWidth = combo02.getWidth()-insets.left-insets.right;
    if(index<0) {
      //@see BasicComboBoxUI#rectangleForCurrentValue
      int buttonSize = combo02.getHeight()-(insets.top+insets.bottom);
      if(arrowButton!=null) {
        buttonSize = arrowButton.getWidth();
      }
      availableWidth -= buttonSize;
      JTextField tf = (JTextField)combo02.getEditor().getEditorComponent();
      insets = tf.getMargin();
      availableWidth -= insets.left;
      //availableWidth -= (insets.left + insets.right);
    }
    String cellText = (value!=null)?value.toString():"";
    FontMetrics fm = getFontMetrics(getFont());
    if(fm.stringWidth(cellText)>availableWidth) {
      String dots = "...";
      int textWidth = fm.stringWidth(dots);
      int nChars = cellText.length() - 1;
      while(nChars>0) {
        textWidth += fm.charWidth(cellText.charAt(nChars));
        if(textWidth > availableWidth) break;
        nChars--;
      }
      setText(dots+cellText.substring(nChars+1));
    }
    return this;
  }
});
}}

**解説 [#qf9b52f8]
標準のJComboBoxでは、長い文字列は右側をクリップするので、上記のサンプルでは左側を切り取り、"..."で置き換えるようにセルレンダラーを変更しています。

例えば、コンボボックスのセルよりファイル名が長くても、拡張子が表示できるようにしたいといった場合に使用します。

ポップアップリストで描画されている場合は、矢印ボタンの幅は無視しています。
エディタ部分で描画されている場合は、矢印ボタンの幅を考慮する必要があります。

Windows環境の1.5と1.6で色々サイズが微妙に異なるようで、うまく表示されない場合があります。
L&Fによって余白などのサイズが微妙に異なる場合がある?ため、うまく表示されないことがあります。

**参考リンク [#u56983b7]
-[[Swing - JTable - right align in cell even if the text is wider than the cell>http://forum.java.sun.com/thread.jspa?threadID=634798]]
-[[Swing - JTable - right align in cell even if the text is wider than the cell>http://forums.sun.com/thread.jspa?threadID=634798]]
--camickr さんの投稿(2005/06/10 5:52)したJTableでのサンプルを参考にしています。

**コメント [#h4fa25ab]
#comment