Пример запуска JProgressBar в модальном окне.
Хотел найти рабочий пример запуска прогресс бара в модальном окне, попадались все какие-то не рабочие примеры. Назрел геморрой. По этому оставлю этот код тут:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ModalProgressBarExample extends JFrame {
private JProgressBar progressBar;
private JButton startButton;
private JDialog dialog;
private Timer timer;
public ModalProgressBarExample() {
setTitle("Modal Progress Bar Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
progressBar = new JProgressBar();
startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Runnable show = () -> {
showProgressBar();
};
SwingUtilities.invokeLater(show);
Runnable r = () -> {
startProgressBar();
};
r.run();
}
});
JPanel panel = new JPanel();
panel.add(startButton);
add(panel, BorderLayout.CENTER);
}
private void showProgressBar() {
dialog = new JDialog(this, "Progress", true);
dialog.setLayout(new FlowLayout());
dialog.setSize(200, 100);
dialog.setLocationRelativeTo(null);
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
dialog.add(progressBar);
dialog.setVisible(true);
}
private void startProgressBar() {
timer = new Timer(100, new ActionListener() {
int value = 0;
@Override
public void actionPerformed(ActionEvent e) {
value++;
progressBar.setValue(value);
System.out.println(value);
if (value == 100) {
timer.stop();
dialog.dispose();
}
}
});
timer.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ModalProgressBarExample().setVisible(true);
}
});
}
}
И геморрой проходит.