0

I have a simple form with a button "Display", when clicked reads the content of "content.txt" file and displays the text in a label which is hidden and is made visible when the button is clicked.

The project works when run as a netbeans project. Through the netbeans IDE I build and package the project into a jar. When executed as a jar this basic functionality can't be seen.

Here is the complete code and "content.txt" resides in the src folder.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

public class TestForm extends javax.swing.JFrame {

    public TestForm() {
        initComponents();
        jLabel1.setVisible(false);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Display");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setBorder(new javax.swing.border.MatteBorder(null));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(155, 155, 155)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(119, 119, 119)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(156, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(jButton1)
                .addGap(51, 51, 51)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(89, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        try {
            URL dir_url = ClassLoader.getSystemResource("content.txt");
            File file = new File(dir_url.toURI());

            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = null;
            StringBuilder stringBuilder = new StringBuilder();
            String ls = System.getProperty("line.separator");

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append(ls);
            }

            jLabel1.setText(stringBuilder.toString());

            jLabel1.setVisible(true);
        }
        catch(URISyntaxException ex){
            ex.printStackTrace();
        }
        catch(FileNotFoundException ex){
            ex.printStackTrace();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }

    }                                        

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

When I run the executable jar it doesn't give me an error but the label with content is not displayed.

When I run the jar using the command line then I get the following exception.

Exception in thread "main" java.lang.UnsupportedClassVersionError: TestForm : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)
Sabra Ossen
  • 161
  • 3
  • 15
  • Three things, try calling `pack` again; try calling `revalidate` and/or `repaint` and combinations of (changing the order) – MadProgrammer Sep 06 '15 at 04:57
  • 1
    Have you tried running the JAR from a command prompt to see if it prints anything? – user253751 Sep 06 '15 at 05:00
  • @MadProgrammer : I tried the different combinations. But nothing worked. – Sabra Ossen Sep 06 '15 at 05:15
  • `URL dir_url = ClassLoader.getSystemResource("content.txt"); File file = new File(dir_url.toURI());` Creating a `File` will fail once the resource is in a Jar. – Andrew Thompson Sep 06 '15 at 05:16
  • @immibis : I have updated the question with the exception I get when I run it from the command line. – Sabra Ossen Sep 06 '15 at 05:19
  • 2
    `UnsupportedClassVersionError` This is typically caused by compiling the app. for a higher Java version that it is running in. The fix is to use the [cross-compilation options](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html#BHCIJIEG) when compiling. – Andrew Thompson Sep 06 '15 at 05:19
  • Your exception is an indication that the user is likely not using Java 8 – MadProgrammer Sep 06 '15 at 05:23
  • You are using the Java 8 compiler on the command line and attempting to run the program in Java 7 (or earlier). You might have it set to run jars with Java 8 in Windows Explorer, and Java 7 from the command line, for some reason. You can use the full path ("C:\Program Files\...etc...\bin\java.exe" including quotes) to run it from the command line. – user253751 Sep 06 '15 at 05:25
  • My netbeans was using Java 8 and my terminal was using Java 7. That was what caused the earlier exception. Now I am getting an " java.lang.IllegalArgumentException: URI is not hierarchical". I am attempting to fix it. – Sabra Ossen Sep 06 '15 at 05:54

1 Answers1

2

The "java.lang.UnsupportedClassVersionError" was due to the fact that my netbeans was using Java 8 and I was trying to run it in the terminal which was running on Java 7.

Once I resolved the above issue and was able to run the jar file in the terminal I got an "java.lang.IllegalArgumentException: URI is not hierarchical" which was because I was trying to access the resource "content.txt" which was within the jar file.

I made the following change in the code where I read the contents of the text file and it fixed the issue.

InputStream stream = getClass().getResourceAsStream("content.txt");

BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
Sabra Ossen
  • 161
  • 3
  • 15