0

I am writing a java app using netbeans IDE and using the gui creator, I created a simple project and some buttons for downloading a jar from a website, but, when I click on the button app freezes/crashes and doesn't allow me to click any buttons or anything else and when I maximize the app then minimize the window turn into black thing. Here is the code generated by gui creator :

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mcsm;

/**
 *
 * @author YReza
 */
import mcsm.download;
public class MCSM1 extends javax.swing.JFrame {

    /**
     * Creates new form MCSM1
     */
    public MCSM1() {
        initComponents();
    }

    /**
     * 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">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MCSM");
        setBackground(new java.awt.Color(0, 0, 0));
        setForeground(java.awt.Color.white);

        jButton1.setText("Run...");
        jButton1.setToolTipText("Run Your Server");
        jButton1.setFocusPainted(false);

        jButton2.setText("Create...");
        jButton2.setToolTipText("Create The Server Using Th Downoaded Jar");
        jButton2.setFocusPainted(false);

        jButton3.setText("Configuration..");
        jButton3.setToolTipText("Configure The Server");
        jButton3.setFocusPainted(false);

        jButton4.setText("Download");
        jButton4.setToolTipText("Download The Jar From Official WebSite");
        jButton4.setBorderPainted(false);
        jButton4.setFocusPainted(false);
        jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton4MouseClicked(evt);
            }
        });

        jProgressBar1.setToolTipText("The Progress Of Your Task");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(122, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3))
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(125, 125, 125))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(130, Short.MAX_VALUE)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addGap(153, 153, 153))
        );

        pack();
    }// </editor-fold>                        

    private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {                                      
        download task = new download();
        task.Task();
    }                                     

    /**
     * @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(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MCSM1.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() {
                new MCSM1().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    public javax.swing.JButton jButton1;
    public javax.swing.JButton jButton2;
    public javax.swing.JButton jButton3;
    public javax.swing.JButton jButton4;
    public javax.swing.JProgressBar jProgressBar1;
    // End of variables declaration                   
    
}

And it is my Download class (I used This method for showing the progress on jprogressbar) :

package mcsm;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
public class download extends javax.swing.JFrame {

    public void Task() {

        MCSM1 jp = new MCSM1();
        JProgressBar jp1 = jp.jProgressBar1;
        try {
            URL url = new URL("https://cdn.getbukkit.org/spigot/spigot-1.16.5.jar");
            try {
                HttpURLConnection httpConnection = (HttpURLConnection)(url.openConnection());
                long completeFileSize = httpConnection.getContentLength();

                java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
                try {
                    byte[] data = new byte[1024];
                    long downloadedFileSize = 0;
                    int x = 0;
                    while ((x = in .read(data, 0, 1024)) >= 0) {
                        downloadedFileSize += x;
                        final int currentProgress = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 100000d);
                        // update progress bar
                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                jp1.setValue(currentProgress);
                            }
                        });
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            } catch (IOException ioe2) {

            }
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        }

        try {
            java.io.FileOutputStream fos = new java.io.FileOutputStream("Spigot.jar");
            java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);

        } catch (FileNotFoundException fnf) {
            fnf.printStackTrace();
        }



        // calculate progress

    }
}

If you want to run it you should have these in lib folder :

enter image description here

kleopatra
  • 51,061
  • 28
  • 99
  • 211
yazdan rezaie
  • 15
  • 1
  • 6
  • please stick to java naming conventions when showing code publicly – kleopatra May 15 '21 at 08:29
  • Your question is confusing. You tagged the question with [tag:javafx] (removed by @kleopatra) and indicate you need the JavaFX libraries, yet your code only references Swing. Are you using JavaFX or Swing? – Slaw May 15 '21 at 08:35
  • As for your problem, it sounds like you're downloading the file on the UI thread (the EDT in Swing, the FX thread in JavaFX). Don't do that. Download the file on a background thread. If you're using Swing then check out `SwingWorker`; if you're using JavaFX then check out `Task`. – Slaw May 15 '21 at 08:36
  • @Slaw I dont know Why but when I remove the javafx libs it does not work and the button style is javafx styled – yazdan rezaie May 15 '21 at 08:37
  • That's really strange. As noted, the code in your question doesn't reference any JavaFX classes so I don't see how that's possible. And Swing is built into the JDK so if you're only using Swing classes then no extra libraries should be needed. – Slaw May 15 '21 at 08:42
  • @Slaw the swing worker did the job, but now the file... why isnt it downloading ?! – yazdan rezaie May 15 '21 at 09:05

0 Answers0