📄 jprogressbardemo.java
字号:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JProgressBarDemo extends JFrame
{
private JProgressBar progressBar; //进度条
private JButton startButton, stopButton; //启动, 暂停, 重启动按钮
private Timer timer; //定时器
public JProgressBarDemo()
{
super("滚动条");
setSize(300, 200);
//获取内容面板
Container container = getContentPane();
//设置内容面板的布局管理器
container.setLayout(new FlowLayout(FlowLayout.CENTER));
container.setBackground(Color.YELLOW);
//创建进度条
progressBar = new JProgressBar();
//设置最小值,最大值,初值
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setValue(0);
//显示进度条进度文本
progressBar.setStringPainted(true);
//显示进度条边框
progressBar.setBorderPainted(true);
//设置进度条大小,背景色,前景色
progressBar.setPreferredSize(new Dimension(250,30));
progressBar.setBackground(Color.WHITE);
progressBar.setForeground(Color.GREEN);
container.add(progressBar);
//创建按钮
startButton = new JButton("开始");
stopButton = new JButton("暂停");
//设置按钮背景颜色
startButton.setBackground(Color.WHITE);
stopButton.setBackground(Color.WHITE);
//设置字体
startButton.setFont(new Font("Serif", Font.PLAIN, 14));
stopButton.setFont(new Font("Serif", Font.PLAIN, 14));
stopButton.setEnabled(false);
//注册监听器
TimerHandler handler = new TimerHandler();
startButton.addActionListener(handler);
stopButton.addActionListener(handler);
container.add(startButton);
container.add(stopButton);
//创建定时器,时间间隔为50毫秒,设置监听器
timer = new Timer(50, handler);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
JProgressBarDemo application = new JProgressBarDemo();
}
class TimerHandler implements ActionListener
{
//处理定时器事件
private int value = 0;
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == timer)
{
value = progressBar.getValue();
if( value < 100)
{
value++;
progressBar.setValue(value);
}
else
{
timer.stop();
startButton.setEnabled(true);
stopButton.setEnabled(false);
}
}
else if(event.getSource() == startButton)
{
if(progressBar.getValue() >= 100)
progressBar.setValue(0);
timer.start();
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
else if(event.getActionCommand().equals("暂停"))
{
timer.stop();
stopButton.setText("重启动");
}
else if(event.getActionCommand().equals("重启动"))
{
timer.restart();
stopButton.setText("暂停");
}
}
} //TimerHandler类结束
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -