解答例 - 実習課題4 - 9.基本的なコンポーネント3
(実習課題4)
以下のプログラムを作成しなさい。
- ウィンドウに含まれるコンポーネントはプログレスバーと「開始」ボタン・「停止」ボタン。
- 「開始」ボタンを押すと、バーが0%から100%まで、1秒ごとに10%ずつ伸びるようにする事。
- 「停止」ボタンを押すと、バーの伸びは停止するようにする事。
- (ヒント)「javax.swing.Timer」クラスを使用する。
解答例
/**
* ProgressFrame.java
* TECHSCORE Javaユーザインタフェース9章 実習課題4
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.ui.chapter9.exercise4;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
public class ProgressBarFrame extends JFrame implements ActionListener {
private JProgressBar bar;
private JButton startButton, stopButton;
private Timer t;
public ProgressBarFrame() {
super("ProgressBarFrame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
t = new Timer(1000, this);
bar = new JProgressBar();
getContentPane().add(bar, BorderLayout.CENTER);
JPanel panel = new JPanel(new GridLayout(1, 2));
getContentPane().add(panel, BorderLayout.SOUTH);
startButton = new JButton("start");
startButton.addActionListener(this);
panel.add(startButton);
stopButton = new JButton("stop");
stopButton.addActionListener(this);
panel.add(stopButton);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
bar.setValue(0);
t.start();
} else if (e.getSource() == stopButton) {
t.stop();
} else if (e.getSource().equals(t)) {
bar.setValue(bar.getValue() + 10);
if (bar.getValue() >= 100) {
bar.setValue(100);
t.stop();
}
}
}
public static void main(String args[]) {
new ProgressBarFrame().setVisible(true);
}
}

