進捗度合いを表す文字列を表示する
広告
進捗バーはデフォルトでは進捗具合を表す棒を表示するだけです。進捗バーでは進捗具合をパーセンテージで表示することが可能です。パーセンテージのような進捗度合いを表す文字列を表示するように設定するにはJProgressBarクラスで用意されている「setStringPainted」メソッドを使います。
setStringPainted public void setStringPainted(boolean b)
stringPainted プロパティーの値を設定します。 このプロパティーは、進捗バー が進捗文字列を描画するかどうかを指定します。デフォルトでは false に設定さ れ、文字列はペイントされません。進捗文字列をサポートしない、または進捗バー が不確定モードのときだけサポートする Look & Feel もあります。 パラメータ: b - 進捗バーに文字列を描画する場合は true
引数に進捗具合の文字列を表示するかどうかを表すboolean型の値を設定します。「true」を設定すると文字列が表示されます。デフォルトは「false」です。
実際の使い方は次のようになります。
JProgressBar bar = new JProgressBar(); bar.setStringPainted(true);
サンプルプログラム
では簡単なサンプルを作成して試してみます。
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
public class JProgressBarTest5 extends JFrame implements ActionListener{
Timer timer;
JButton startButton;
JButton stopButton;
JProgressBar bar;
JLabel label;
int count;
public static void main(String[] args){
JProgressBarTest5 frame = new JProgressBarTest5();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(10, 10, 300, 200);
frame.setTitle("タイトル");
frame.setVisible(true);
}
JProgressBarTest5(){
count = 0;
label = new JLabel("Not Start");
JPanel labelPanel = new JPanel();
labelPanel.add(label);
startButton = new JButton("start");
startButton.addActionListener(this);
startButton.setActionCommand("start");
stopButton = new JButton("stop");
stopButton.addActionListener(this);
stopButton.setActionCommand("stop");
stopButton.setEnabled(false);
JPanel buttonPanel = new JPanel();
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
bar = new JProgressBar(0, 200);
bar.setStringPainted(true);
bar.setValue(0);
JPanel barPanel = new JPanel();
barPanel.add(bar);
timer = new Timer(100 , this);
timer.setActionCommand("timer");
getContentPane().add(labelPanel, BorderLayout.PAGE_START);
getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
getContentPane().add(barPanel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e){
String cmd = e.getActionCommand();
if (cmd.equals("start")){
startButton.setEnabled(false);
stopButton.setEnabled(true);
timer.start();
}else if (cmd.equals("stop")){
startButton.setEnabled(true);
stopButton.setEnabled(false);
timer.stop();
}else if (cmd.equals("timer")){
label.setText(count + " count");
if (count >= 200){
startButton.setEnabled(true);
stopButton.setEnabled(false);
timer.stop();
bar.setValue(count);
count = 0;
}else{
count++;
bar.setValue(count);
}
}
}
}
上記をコンパイルした後で実行すると次のように表示されます。
デフォルトでは進捗文字列としてパーセンテージで表示されます。実際に処理を開始すると次のように表示されます。
なお表示されている値は進捗バーに設定している値ではありません。進捗バーに設定された最小値及び最大値の範囲に対する現在の値の進捗の割合を0%~100%の範囲で表示します。
( Written by Tatsuo Ikura )
著者 / TATSUO IKURA
これから IT 関連の知識を学ばれる方を対象に、色々な言語でのプログラミング方法や関連する技術、開発環境構築などに関する解説サイトを運営しています。