Сделайте заставку с индикатором прогресса, как Eclipse
мой основной класс загружает конфигурацию из файла, а затем показывает кадр. Я хочу сделать заставку с индикатором прогресса, таким как Eclipse, чтобы прогресс увеличивался во время загрузки файла, а всплеск исчезал после загрузки файла. Затем загружается мой основной фрейм.
MainClass код:
public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext(
    "classpath:/META-INF/spring/applicationContext.xml");
  // splash with progress load till this file is loaded
  UserDao userDao = context.getBean(UserDao.class);
  isRegistered = userDao.isRegistered();
  System.out.println("registered: " + isRegistered);
  if (isRegistered) {
    // progress finish and hide splash
    log.debug("user is registered"); // show frame1
  } else {
    // progress finish and hide splash
    log.debug("user is not registered"); // show frame2
  }
}
у меня нет большого опыта работы с Swing, поэтому, пожалуйста, посоветуйте, как это сделать.
обновление: Я нашел следующий пример, но у него мало проблем:
- когда счетчик добирается до указанного числа, он должен остановиться на (300), он продолжает считать навсегда, не останавливая таймер и скрывая заставку. 
- 
Я хочу привязать счетчик к загрузке файла, поэтому, пока файл загружен, прогресс загружается до тех пор, пока файл не будет загружен, затем прогресс завершается и заставка исчезает. @SuppressWarnings("serial") @Component public class SplashScreen extends JWindow { static boolean isRegistered; static Log log = LogFactory.getLog(SplashScreen.class); private static JProgressBar progressBar = new JProgressBar(); private static SplashScreen execute; private static int count; private static Timer timer1; public SplashScreen() { Container container = getContentPane(); container.setLayout(null); JPanel panel = new JPanel(); panel.setBorder(new javax.swing.border.EtchedBorder()); panel.setBackground(new Color(255, 255, 255)); panel.setBounds(10, 10, 348, 150); panel.setLayout(null); container.add(panel); JLabel label = new JLabel("Hello World!"); label.setFont(new Font("Verdana", Font.BOLD, 14)); label.setBounds(85, 25, 280, 30); panel.add(label); progressBar.setMaximum(50); progressBar.setBounds(55, 180, 250, 15); container.add(progressBar); loadProgressBar(); setSize(370, 215); setLocationRelativeTo(null); setVisible(true); } public void loadProgressBar() { ActionListener al = new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { count++; progressBar.setValue(count); if (count == 300) { timer1.stop(); execute.setVisible(false); return; } } }; timer1 = new Timer(50, al); timer1.start(); } public static void main(String[] args) { execute = new SplashScreen(); ApplicationContext context = new ClassPathXmlApplicationContext( "classpath:/META-INF/spring/applicationContext.xml"); UserDao userDao = context.getBean(UserDao.class); isRegistered = userDao.isRegistered(); if (isRegistered) { // show frame 1 } else { // show frame 2 } } }
2 ответов
когда счетчик дойдет до указанного номера, он должен остановиться на (300) он продолжает считать вечно, не останавливая таймер и скрывая заставка.
код ниже, кажется, отлично работает (с фатальным недостатком счетчик может занять больше времени, чем загрузка файла и наоборот):
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SplashScreen extends JWindow {
    static boolean isRegistered;
    private static JProgressBar progressBar = new JProgressBar();
    private static SplashScreen execute;
    private static int count;
    private static Timer timer1;
    public SplashScreen() {
        Container container = getContentPane();
        container.setLayout(null);
        JPanel panel = new JPanel();
        panel.setBorder(new javax.swing.border.EtchedBorder());
        panel.setBackground(new Color(255, 255, 255));
        panel.setBounds(10, 10, 348, 150);
        panel.setLayout(null);
        container.add(panel);
        JLabel label = new JLabel("Hello World!");
        label.setFont(new Font("Verdana", Font.BOLD, 14));
        label.setBounds(85, 25, 280, 30);
        panel.add(label);
        progressBar.setMaximum(50);
        progressBar.setBounds(55, 180, 250, 15);
        container.add(progressBar);
        loadProgressBar();
        setSize(370, 215);
        setLocationRelativeTo(null);
        setVisible(true);
    }
    private void loadProgressBar() {
        ActionListener al = new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                count++;
                progressBar.setValue(count);
                System.out.println(count);
                if (count == 300) {
                    createFrame();
                    execute.setVisible(false);//swapped this around with timer1.stop()
                    timer1.stop();
                }
            }
            private void createFrame() throws HeadlessException {
                JFrame frame = new JFrame();
                frame.setSize(500, 500);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        };
        timer1 = new Timer(50, al);
        timer1.start();
    }
    public static void main(String[] args) {
        execute = new SplashScreen();
    }
};
Я хочу привязать счетчик к загрузке файла, поэтому, пока файл загруженный прогресс загружается до тех пор, пока файл не будет загружен затем прогресс завершается, и экран-заставка исчезает.
вы должны взглянуть на ProgressMonitor и ProgressMonitorInputStream С помощью Task затем вы можете проверить, когда файл полностью прочитать и конец SplashScreen. см.здесь для некоторых большой учебник и объяснение
Java имеет встроенный SplashScreen класс только для этой цели.  Есть учебник о том, как его использовать здесь.
