Pregunta

Estoy haciendo un proyecto y necesito una barra de progreso. Tengo la clase con el temporizador y funciona bien cuando incluyo un principal; Pero cuando trato de llamarlo en el método Maingui, todo es negro hasta que llega al 100% y luego aparece.

package microproject.resources;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Timer extends JFrame {

    JProgressBar current;
    JTextArea out;
    JButton find;
    Thread runner;
    int num = 0;
    int length = 0;

    public Timer() {
        setTitle("Progress");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        length = Integer.parseInt(JOptionPane.showInputDialog(null, "How many seconds:"));

        JPanel p = new JPanel(new GridLayout(1,1));
        p.setPreferredSize(new Dimension(300,65));
        current = new JProgressBar(0, length);
        current.setPreferredSize(new Dimension(250,50));
        current.setValue(0);
        current.setStringPainted(true);
        p.add(current);
        setVisible(true);
        setContentPane(p);
        pack();
        setVisible(true);
        iterate();
    }

    public void iterate() {
        while(num < length +1) {
            current.setValue(num);
            try {
                Thread.sleep(1000);
            } catch(InterruptedException e) {}
            num += 1;
        }

    }

    public static void main(String[] args) {
        Timer f = new Timer();
    }
}

Este es el código para la clase de temporizador ^

package microproject.resources;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class GUIMain extends JFrame {

    public static void main(String []args){            
        GuiFrame();        
    }    

    public static void GuiFrame(){
        JFrame frame = new JFrame("Casino Royal3");
        frame.setSize(811,577);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

        frame.setLayout(new GridLayout(2,1));
        frame.setResizable(false);
        JPanel PNorth = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0));
        JPanel PSouth = new JPanel(new BorderLayout());


        //Creating Image for Casino Button
        ImageIcon img1 = new ImageIcon("src\\Casino.jpg");
        final JButton btn1 = new JButton(img1);
        btn1.setPreferredSize(new Dimension(550,274));
        btn1.setMargin(new Insets(0,0,0,0));
        PNorth.add(btn1, BorderLayout.EAST);
        btn1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                btn1.setIcon(new ImageIcon("src\\Casino2.jpg"));
            }
        });

        //Creating Image for Sheridan Label
        ImageIcon img2 = new ImageIcon("src\\SHERIDAN_LOGO.jpg");
        JButton btn2 = new JButton(img2);
        btn2.setMargin(new Insets(0,0,0,0));
        PNorth.add(btn2);
        btn2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ImageIcon instruc = new ImageIcon("src\\Instructions.jpg");
                JLabel instructions = new JLabel(instruc);
                JOptionPane.showConfirmDialog(null, instructions, "instructions", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE);
            }
        });

        JPanel timmus = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0));
        timmus.setPreferredSize(new Dimension(166, 273));
        timmus.setBackground(Color.BLUE);

        ImageIcon time = new ImageIcon("src\\Timer.jpg");
        JButton timer = new JButton(time);
        timer.setMargin(new Insets(0,0,0,0));
        timer.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Timer f = new Timer();
            }
        });
        timmus.add(timer);

        ImageIcon mus = new ImageIcon("src\\music.jpg");
        JButton music = new JButton(mus);
        music.setMargin(new Insets(0,0,0,0));
        timmus.add(music);

        JPanel games = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0));
        games.setPreferredSize(new Dimension(500,279));
        games.setBackground(Color.BLUE);

        ImageIcon calculator = new ImageIcon("src\\Calculator.jpg");
        JButton calc = new JButton(calculator);
        calc.setMargin(new Insets(0,0,0,0));
        calc.setPreferredSize(new Dimension(166,273));
        games.add(calc);
        calc.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Calculator c1 = new Calculator();
            }
        });

        ImageIcon g1 = new ImageIcon("src\\250Hangman.jpg");
        JButton game1 = new JButton(g1);
        //game1.setBackground(Color.WHITE);
        game1.setMargin(new Insets(0,0,0,0));
        game1.setPreferredSize(new Dimension(166,273));
        games.add(game1);
        game1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Hangman h1 = new Hangman();
            }
        });


        ImageIcon g2 = new ImageIcon("src\\Minesweeper.jpg");
        JButton game2 = new JButton(g2);
    //    game2.setBackground(Color.WHITE);
        game2.setMargin(new Insets(0,0,0,0));    
        game2.setPreferredSize(new Dimension(166,273));
        games.add(game2);

        PSouth.add(timmus, BorderLayout.CENTER);
        PSouth.add(games, BorderLayout.EAST);

        frame.add(PNorth, BorderLayout.NORTH);
        frame.add(PSouth, BorderLayout.SOUTH);

        frame.setVisible(true);
        frame.pack();
    }
}

Ese es todo el programa, el Timer ActionListener se llama "Temporizador"

Gracias por adelantado

¿Fue útil?

Solución

Bienvenido al maravilloso mundo del hilo de despacho de eventos bloqueados (y la violación del hilo inicial)

Básicamente, Swing es un entorno de enhebrado único, se espera que todas las actualizaciones y modificaciones a la interfaz de usuario se ejecuten dentro del contexto del hilo de despacho de eventos (también conocido como EDT).

El EDT es responsable de, entre otras cosas, procesar solicitudes de repintado. Si, por alguna razón, bloquea este hilo (por ejemplo, utilizando un bucle de ejecución largo o bloqueando IO), evitará que el EDT procese nuevas solicitudes de pintura, lo que hace que su programa haya colgado ... porque esencialmente él esencialmente. posee.

La razón por la que puede ver una diferencia entre correr Timer Directamente y usarlo en su GUI es porque cuando se inicia la aplicación, se ejecutará dentro, lo que comúnmente se conoce como, el hilo "principal".

Cuando crea por primera vez un contenedor de swing de nivel superior, se inicia el EDT (que es un hilo separado), lo que significa que la interfaz de usuario aparecerá en su propio hilo, pero la aplicación continuará ejecutándose en el hilo "principal", lo que permite que su iterate Método para ejecutarse independientemente del EDT.

Sin embargo, cuando intenta ejecutarlo desde su GUI, todo se ejecuta dentro del contexto del EDT, lo que hace que se bloquee.

Empiece por echar un vistazo a

Para solucionar el problema, según su código de ejemplo, sugeriría usar un SwingWorker. Esto le permitirá ejecutar su "tarea de larga duración" en un hilo de fondo, pero proporciona una serie de métodos que le permiten volver a sincronizar sus actualizaciones al EDT. Esto es muy importante, ya que nunca debe intentar actualizar la interfaz de usuario o cambiar su estado desde cualquier hilo que el EDT.

Echa un vistazo a Hilos de trabajadores y swingworker para más detalles

Y si es necesario, algunos ejemplos ...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top