The JProgressBar does not appear when I execute it

4

I have a JFrame frmMenuPrincipal where it contains a JMenuBar and that JMenuBar contains a JMenu mConsulta and within that JMenu contains a JMenuItem miCobranza . When I click on the JMenuItem I get a window and in that window I have to see a JProgressBar that is loading and when finished loading open JInternalFrame but I do not see the JProgressBar bone when the window is not displayed nothing in it.

JMenuItem code with which I call the JProgressBar and at the same time the JInternalFrame :

protected void miCobranzaActionPerformed(ActionEvent e) {
        frmProgressBar p = new frmProgressBar();
        p.setVisible(true);
        frmCobranzaDudosa x = new frmCobranzaDudosa();
        dpContenedor.add(x);
        x.setVisible(true);
    }

Window code of JprogressBar ( JFrame frmProgressBar ):

    package Vista;

import java.awt.EventQueue;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JSeparator;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.JLabel;
import javax.swing.ImageIcon;

@SuppressWarnings("serial")
public class frmProgressBar extends JFrame {

    private JPanel contentPane;
    private JProgressBar progressBar;
    private Timer timer;
    private TimerTask task;
    private int numero;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    frmProgressBar frame = new frmProgressBar();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public frmProgressBar() {
        setTitle("Procesando...");
        setResizable(false);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setBounds(100, 100, 450, 183);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JSeparator separator = new JSeparator();
        separator.setBounds(10, 11, 414, 2);

        JSeparator separator_1 = new JSeparator();
        separator_1.setBounds(10, 142, 415, 2);

        progressBar = new JProgressBar();
        progressBar.setBounds(10, 110, 415, 21);
        progressBar.setStringPainted(true);
        contentPane.setLayout(null);
        contentPane.add(progressBar);
        contentPane.add(separator_1);
        contentPane.add(separator);

        JLabel label = new JLabel("");
        label.setIcon(new ImageIcon(frmProgressBar.class.getResource("/Imagenes/cargando.gif")));
        label.setBounds(183, 24, 72, 75);
        contentPane.add(label);

        cargarBarra();
    }

    private void cargarBarra() {
        timer = new Timer();
        task = new TimerTask() {
            public void run() {
                if (numero >= 100) {
                    timer.cancel();
                    dispose();
                }
                int nuevo = (int) (Math.random() * 4) + 1;
                progressBar.setValue(numero);
                numero = numero + nuevo;
            }
        };
        timer.scheduleAtFixedRate(task, 0, 100);
    }
}

So it appears to me when I run the progressBar:

    
asked by Angelica 20.04.2017 в 17:55
source

2 answers

1

If you build the progress bar and the JInternalFrame in sequence, both will run in the UI-Thread. This ends the progress bar, then the JInternalFrame is created. You can solve if you design the JInternalFrame with a lightweight constructor and a init() method that does the heavy lifting, while driving a variable with the percentage of work in JInternalFrame .

Example:

import java.awt.EventQueue;
import java.awt.Frame;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JDialog;
import javax.swing.JSeparator;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.JLabel;
import javax.swing.ImageIcon;

import classes.Dialog.InternalFrame;

// se hace una subclase de JDialog en vez de JFrame para hacer la barra de progreso modal
// así el usuario no puede hacer acciones en la UI mientras tanto    
@SuppressWarnings("serial")
public class ProgressBar extends JDialog {

    private JPanel contentPane;
    private JProgressBar progressBar;
    private Timer timer;
    private TimerTask task;
    private int numero;
    private InternalFrame frame;
    private Frame owner;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    //ProgressBar frame = new ProgressBar();
                    //frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public ProgressBar(InternalFrame frame, Frame owner, boolean modal) {
        super(owner,modal);
        this.frame=frame;
        this.owner=owner;
        setTitle("Procesando...");
        setResizable(false);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setBounds(100, 100, 450, 183);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JSeparator separator = new JSeparator();
        separator.setBounds(10, 11, 414, 2);

        JSeparator separator_1 = new JSeparator();
        separator_1.setBounds(10, 142, 415, 2);

        progressBar = new JProgressBar();
        progressBar.setBounds(10, 110, 415, 21);
        progressBar.setStringPainted(true);
        contentPane.setLayout(null);
        contentPane.add(progressBar);
        contentPane.add(separator_1);
        contentPane.add(separator);

        JLabel label = new JLabel("cargando");
        label.setIcon(new ImageIcon(ProgressBar.class.getResource("/Imagenes/cargando.gif")));
        label.setBounds(183, 24, 72, 75);
        contentPane.add(label);

        cargarBarra();
    }

    private void cargarBarra() {
        timer = new Timer();
        task = new TimerTask() {
            public void run() {
                // en vez de numeros aleatorios se usa el porcentaje del JInternalFrame
                if (frame.porcentaje >= 100) {
                    timer.cancel();
                    dispose();
                }
                progressBar.setValue(frame.porcentaje);
            }
        };
        timer.scheduleAtFixedRate(task, 0, 100);
        // aqui se ejecuta la terminación de tu frame en una hebra propia
        new Thread(new Runnable(){
            @Override
            public void run() { frame.init(owner); }
        }).start();
    }

} 

I commented on the main changes in the progress bar. The majority is found in the cargarBarra();

method

Here I have set an example of a JFrame with a menu where you can create a new InternalFrame with the option "New". The InternalFrame is subclass of JInternalFrame and takes a method init() for the heavy construction work and a field for the completion percentage, which the progress bar accesses. That gives a more "real" value to the termination state.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

public class Dialog extends JFrame {

    private JPanel contentPane;
    private JMenuBar menuBar;


    public static class InternalFrame extends JInternalFrame{

        public int porcentaje=0;

        public InternalFrame(String title, boolean resize, boolean close, boolean max, boolean icon){
            super(title, resize, close, max, icon);
            InternalFrame.this.setSize(150, 100);
            InternalFrame.this.setBounds(100, 100, 150, 100);
            JTextArea textArea = new JTextArea();
            setContentPane(textArea);
            textArea.append("contenido");   
        }

        public void init(Frame padre){
            System.out.println("progbar visible");
            for (int i = 0;i<100;i++){
                System.out.println(i);
                cargaPesada(i);
            }
            // al fin del trabajo pesado, el InternalFrame se hace visible y se agrega al padre
            setVisible(true);
            padre.add(this);
        }

        public void cargaPesada(int i){
                try {
                    // eso simula código para construir con actualisación del porcentaje de termino
                    Thread.sleep(50);
                    porcentaje++;
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }

    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Dialog frame = new Dialog();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Dialog() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 600, 300);
        this.setTitle("JInternalFrameDemo");
        menuBar = new JMenuBar();
        JMenu frame = new JMenu("Frame");
        JMenuItem nuevoFrame = new JMenuItem("Nuevo");
        frame.add(nuevoFrame);
        nuevoFrame.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                InternalFrame iFrame = new InternalFrame("iFrame",false,true,false,false);
                ProgressBar p = new ProgressBar(iFrame, Dialog.this, true);
                p.setVisible(true);
            }
        });
        menuBar.add(frame);
        this.setJMenuBar(menuBar);

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
    }

}
    
answered by 21.04.2017 в 18:59
0

This is an old example that I had, the one that I mentioned to you I have it in another PC that I do not have at this moment, but it is similar

    import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.Timer;

public class bienvenida extends javax.swing.JFrame {
        private Timer mitiempo;
        private Menu mimenu;
        private bienvenida mibien;
    /**
     * Creates new form bienvenida
     */

    public bienvenida(Menu a) {
        initComponents();
        mimenu=a;
        mitiempo=new Timer(50,new Progreso());
        mitiempo.start();
        mimenu.setVisible(true);
        mibien=this;



    }


    public class Progreso implements ActionListener
            {


            public void actionPerformed(ActionEvent event)
            {
             int n=jProgressBar1.getValue();
             if(n<100)
             {
                 n++;
                 jProgressBar1.setValue(n);
             }
             else
             {
                 mitiempo.stop();
                 JOptionPane.showMessageDialog(null,"se acabo");
                 mimenu.setVisible(true);
                 mibien.dispose();
             }
             }
            }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jProgressBar1 = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("BIENVENIDA");
        setLocationByPlatform(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(66, 66, 66)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(48, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(213, Short.MAX_VALUE)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(60, 60, 60))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(bienvenida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(bienvenida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(bienvenida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(bienvenida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {


            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JProgressBar jProgressBar1;
    // End of variables declaration//GEN-END:variables
}

Where you can do that in this method:

public class Progreso implements ActionListener
        {


        public void actionPerformed(ActionEvent event)
        {
         int n=jProgressBar1.getValue();
         if(n<100)
         {
             n++;
             jProgressBar1.setValue(n);
         }
         else
         {
             mitiempo.stop();
             JOptionPane.showMessageDialog(null,"se acabo");
             mimenu.setVisible(true);
             mibien.dispose();
         }
         }
        }

There you do the if , you can make that in X percentage call the query method and then, 100% show your Jframe or what you want to do then

    
answered by 20.04.2017 в 20:07