---
category: swing
folder: ProgressStringAlignment
title: JProgressBarの進捗文字列の字揃えを変更する
tags: [JProgressBar, JLabel, BorderLayout, Alignment]
author: aterai
pubdate: 2012-04-02T16:48:11+09:00
description: JProgressBarの進捗文字列をJLabelにして、字揃えなどを変更します。
image: https://lh5.googleusercontent.com/-zRMPjXT7do4/T3lYdJUnilI/AAAAAAAABLA/kcpMYSYoklM/s800/ProgressStringAlignment.png
---
* Summary [#summary]
`JProgressBar`の進捗文字列を`JLabel`にして、字揃えなどを変更します。
#download(https://lh5.googleusercontent.com/-zRMPjXT7do4/T3lYdJUnilI/AAAAAAAABLA/kcpMYSYoklM/s800/ProgressStringAlignment.png)
* Source Code Examples [#sourcecode]
#code(link){{
class StringAlignmentProgressBar extends JProgressBar {
private final JLabel label;
// private transient ChangeListener changeListener;
protected StringAlignmentProgressBar(BoundedRangeModel model, int horizAlignment) {
super(model);
label = new JLabel(" ", horizAlignment);
}
@Override public void updateUI() {
removeAll();
// removeChangeListener(changeListener);
super.updateUI();
setLayout(new BorderLayout());
// changeListener = e -> label.setText(getString());
// addChangeListener(changeListener);
EventQueue.invokeLater(() -> {
add(label);
label.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
});
}
@Override protected ChangeListener createChangeListener() {
return e -> label.setText(getString());
}
}
}}
* Description [#explanation]
* Description [#description]
上記のサンプルでは、`JProgressBar`のレイアウトを`BorderLayout`に変更し、水平方向の配置方法を設定した`JLabel`を追加して字揃えを変更しています。
- `JProgressBar#setStringPainted(true)`を同時に使用すると`2`重に表示される
- 進捗状況に応じた文字色の変化には対応していない
- `NimbusLookAndFeel`を適用した`JProgressBar`に`TitledBorder`を設定するとデフォルトの`JProgressBar#setStringPainted(true)`で表示される進捗文字列の垂直位置がずれる場合がある
* Reference [#reference]
- [[JProgressBarの文字列をJLayerを使って表示する>Swing/ProgressStringLayer]]
* Comment [#comment]
#comment
#comment