Swing/JustifiedLabel のバックアップ(No.5)
- バックアップ一覧
 - 差分 を表示
 - 現在との差分 を表示
 - 現在との差分 - Visual を表示
 - ソース を表示
 - Swing/JustifiedLabel へ行く。
  
- 1 (2008-03-31 (月) 00:41:18)
 - 2 (2008-03-31 (月) 18:36:51)
 - 3 (2008-04-03 (木) 12:57:37)
 - 4 (2011-03-29 (火) 16:54:25)
 - 5 (2012-11-04 (日) 23:04:18)
 - 6 (2012-11-16 (金) 18:50:20)
 - 7 (2013-01-01 (火) 19:54:35)
 - 8 (2014-04-02 (水) 14:49:49)
 - 9 (2014-10-05 (日) 03:12:52)
 - 10 (2014-11-22 (土) 03:59:58)
 - 11 (2015-02-25 (水) 17:37:15)
 - 12 (2015-03-24 (火) 16:08:05)
 - 13 (2015-06-22 (月) 17:58:09)
 - 14 (2015-07-26 (日) 20:02:46)
 - 15 (2015-07-27 (月) 01:04:50)
 - 16 (2017-04-03 (月) 19:44:28)
 - 17 (2018-02-21 (水) 13:05:16)
 - 18 (2019-05-22 (水) 19:35:38)
 - 19 (2020-02-05 (水) 16:45:49)
 - 20 (2021-07-28 (水) 05:21:23)
 - 21 (2025-01-03 (金) 08:57:02)
 - 22 (2025-01-03 (金) 09:01:23)
 - 23 (2025-01-03 (金) 09:02:38)
 - 24 (2025-01-03 (金) 09:03:21)
 - 25 (2025-01-03 (金) 09:04:02)
 - 26 (2025-06-19 (木) 12:41:37)
 - 27 (2025-06-19 (木) 12:43:47)
 
 
TITLE:JLabelの文字揃え
Posted by aterai at 2008-03-31
JLabelの文字揃え
JLabelで、左右中央両端などの文字揃えをテストします。
- &jnlp;
 - &jar;
 - &zip;
 
サンプルコード
JLabel l0 = new JLabel("打率");
JLabel l1 = new JLabel("打率", JLabel.RIGHT);
JLabel l2 = new JustifiedLabel("打率");
JLabel l3 = new JLabel("出塁率", JLabel.CENTER);
JLabel l4 = new JustifiedLabel("出塁率");
JLabel l5 = new JustifiedLabel("チーム出塁率");
View in GitHub: Java, Kotlinclass JustifiedLabel extends JLabel {
  private GlyphVector gvtext;
  private int prev_width = -1;
  public JustifiedLabel() {
    this(null);
  }
  public JustifiedLabel(String str) {
    super(str);
  }
  @Override protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    Insets i = getInsets();
    int w = getWidth() - i.left - i.right;
    if(w!=prev_width) {
      gvtext = getWrappedGlyphVector(
        getText(), w, getFont(), g2.getFontRenderContext());
      prev_width = w;
    }
    if(gvtext!=null) {
      g2.drawGlyphVector(gvtext,i.left,(getHeight()+getFont().getSize())/2);
    }else{
      super.paintComponent(g);
    }
  }
  private GlyphVector getWrappedGlyphVector(
      String str, float wrapping, Font font, FontRenderContext frc) {
    GlyphVector gv   = font.createGlyphVector(frc, str);
    float ga = 0.0f;
    for(int i=0;i<gv.getNumGlyphs();i++) {
      ga = ga + gv.getGlyphMetrics(i).getAdvance();
    }
    if(wrapping<ga) return null;
    float xx = (wrapping-ga) / (float)(gv.getNumGlyphs()-1);
    float xpos = 0.0f;
    Point2D gmPos = new Point2D.Double(0.0d, 0.0d);
    for(int i=0;i<gv.getNumGlyphs();i++) {
      GlyphMetrics gm = gv.getGlyphMetrics(i);
      gmPos.setLocation(xpos, 0);
      gv.setGlyphPosition(i, gmPos);
      xpos = xpos + gm.getAdvance() + xx;
    }
    return gv;
  }
}
解説
JLabelの文字揃えは、デフォルトが左揃えで、その他に右揃え、中央揃えがあります。両端揃え(文字の均等割り付け)は存在しないようなので、上記のサンプルでは、JustifiedLabel*1を作成して使用しています。
