I’m using eclipse and I’m creating this java applet
but I keep getting below error when I tried to run an applet. I know it’s deprecated in the new version (I even tired 1.8) but is there something I can use to make it work?
Error: Could not find or load main class sun.applet.AppletViewer
Caused by: java.lang.ClassNotFoundException: sun.applet.AppletViewer
Rmahajan
1,2631 gold badge13 silver badges22 bronze badges
asked Feb 3, 2019 at 18:13
Charles XavierCharles Xavier
1,0153 gold badges14 silver badges32 bronze badges
11
I think you are using jdk-13. However, Applets support jdk-8 and lower.
The current solution for you would be:
- Install jdk-8 and open Eclipse.
- Go to Window -> Preferences -> Add -> next and find your jvm folder(e.g. /usr/lib/jvm).
- From there select jdk-8.
- After adding jdk-8, remove the jdk-13 from Preferences.
After everything here, it should start working. If you encounter the error
Exception in thread «main» java.awt.AWTError: Assistive Technology not found: org.GNOME.Accessibility.AtkWrapper
you can simply run this command
sudo sed -i -e '/^assistive_technologies=/s/^/#/' /etc/java-*-openjdk/accessibility.properties
David C.
1,9042 gold badges18 silver badges29 bronze badges
answered Jan 19, 2020 at 18:34
For support of Applets in Netbeans, you can edit the path to your JDK in netbeans config file which is found in /netbeans-8.2/etc/netbeans.conf. Change the line netbeans_jdkhome=»» to your JDK 8 e.g netbeans_jdkhome=»/usr/java/jdk1.8.0_241-amd64/»
answered Nov 27, 2020 at 12:20
novac_33 2 / 2 / 0 Регистрация: 26.04.2016 Сообщений: 42 |
||||||||
1 |
||||||||
07.10.2016, 00:17. Показов 2810. Ответов 2 Метки нет (Все метки)
Здравствуйте. Возникла следующая проблема: при попытке выполнения команды appletviewer SimpleApplet.java в cmd получаю ошибку:
Код SimpleApplet.java:
Тему апплетов только начал, поэтому не получается нормально разобраться, в чем проблема.
__________________
0 |
some_name Вежливость-главное оружие 233 / 234 / 86 Регистрация: 19.02.2013 Сообщений: 1,446 |
||||||||||||
07.10.2016, 00:40 |
2 |
|||||||||||
в начале выполните
чтобы скомпилировать файл.
а уж потом выполните
1 |
2 / 2 / 0 Регистрация: 26.04.2016 Сообщений: 42 |
|
07.10.2016, 06:04 [ТС] |
3 |
some_name, спасибо, затупил. Раньше с консолью не работал, всё в NetBeans писал и как-то забыл, что нужно компилировать вручную тоже.
0 |
Может кто знает как решить такую проблему..
При написании программы в eclipse все отлично компилируется и работает, но при попытки запустить программу через командную строку ошибка «Could not find or load main class helloworld»
Для примера написал «Hello World!»
package ru.sers.helloworld;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
В среде все работает, а вот при попытки запустить скомпелированный файл «HelloWorld.class» получается ошибка.
Может кто подскажет с чем это может быть связано?
-
Вопрос заданболее трёх лет назад
-
26205 просмотров
Пригласить эксперта
опишите последовательность действий.
Компиляция?
Запуск?
Имена классов же регистрозависимые? helloworld и HelloWorld разные классы
столкнулся с аналогичной ошибкой Error: Could not find or load main class sample.Main при экспериментах на Intellij Idea c Kotlin+JavaFX
лечится в т.ч. следующим неудобным «костылем»: Если появилась эта ошибка -удалите подкаталог production (со всем содержимыми результатами предыдущей сборки в ) в каталоге out.
После этого успешно собирается, но часто только 1 раз (потом опять..и опять удалять этот каталог).
Как кардинально лечить не нашел. Кто что предложит?
Если создавали главный класс с методом Main в пакете, то нужно в терминале перейти в каталог с основным проектом и набрать команду == например (java com.javacourse.se.lesson1.Main)
терминал: PS D:Java_Projeckt_intellij2020_2_3outproductionHelloWorld> java com.javacourse.se.lesson1.Main
3 дня мучался с этим вопросом! Перерыл всё. Считаю своим долгом поделиться.
Начал по книге Якова Файна изучать Java. С командной строки программа компилировалась. В Eclipse IDE не пошла. Лазил в настройки Patch и CLASSPATCH, удалял свои папки из Директории Workspace и снова возвращал и еще как то извращался.
В итоге по видео 5 летней давности https://youtu.be/mDyXljx8dMI (Основы Java. Урок 6: Первая программа на Java в Eclipse (Vladimir Vysokomornyi)) заменил библиотеку по умолчанию в Eclipse — JRE на JDK. И заработало. Правда простейшая программа думает сек 15.
В открытом проекте жму File/Properties/, затем в левой части выбрал Java Build Path, а в центральной части вкладку Libraries.
Выбрал папку JRE и нажал кнопку Remove. Выбрал надпись Modulepath, только после этого стала активной кнопка справа Add Library. Нажимаю. Выбираю JRE System Library, затем кнопка Next>, активирую надпись Alternative JRE и в выпадающем списке выбираю jdk-15.0.1.
Нажимаю Finish и Apply and Close.
Только для того, чтобы jdk-15.0.1 появилась в выпадающем списке, сначала нужно было подключить эту библиотеку, как в видеоуроке. У меня не подключилась, было написано The JRE name is already in use (уже используется).
Всем удачи и терпения
-
Показать ещё
Загружается…
09 февр. 2023, в 15:56
20000 руб./за проект
09 февр. 2023, в 15:55
75000 руб./за проект
09 февр. 2023, в 15:13
2000 руб./за проект
Минуточку внимания
1. Overview
Occasionally when we run a Java program, we might see “Could not find or load main class.” It’s easy to guess the reason: The JVM failed to find the main class and gave this error. But why couldn’t it?
In this tutorial, we’ll discuss the probable reasons for failure to find the main class. We’ll also see how to fix them.
2. Sample Program
We’ll start with a HelloWorld program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world..!!!");
}
}
Now let’s compile it:
$ javac HelloWorld.java
Here, the compiler will generate a .class file for our program. This .class file will be generated in the same directory. The .class file will have the same name as the class name given in the Java program. This .class file is executable.
In the following sections, we’ll run this .class file and try to understand the probable reasons for error “Could not find or load main class.”
3. Wrong Class Name
To run a .class file generated by Java compiler, we can use this command:
java <.class filename>
Now let’s run our program:
$ java helloworld
Error: Could not find or load main class helloworld
And it failed with the error “Could not find or load main class helloworld.”
As discussed earlier, the compiler will generate the .class file with the exact same name given to the Java class in the program. So in our case, the main class will have the name HelloWorld, not helloworld.
Let’s give it one more try with correct casing:
$ java HelloWorld
Hello world..!!!
This time it ran successfully.
3.1. File Extension
To compile a Java program, we must provide the file name with its extension (.java):
$ javac HelloWorld.java
But to run a .class file, we need to provide the class name, not the file name. So there is no need to provide the .class extension:
$ java HelloWorld.class
Error: Could not find or load main class HelloWorld.class
Again, let’s run our program using the correct class name:
$ java HelloWorld
Hello world..!!!
4. Java Package Names
In Java, we keep similar classes together in what we call a package.
Let’s move HelloWorld class into the com.baeldung package:
package com.baeldung;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world..!!!");
}
}
Now let’s compile and run the updated HelloWorld program like before:
$ java HelloWorld
Error: Could not find or load main class HelloWorld
But again, we get the error “Could not find or load main class HelloWorld.”
Let’s try to understand what we missed here.
To run a Java class that is in a package, we must provide its fully qualified name. So in our case, HelloWorld‘s fully qualified name is com.baeldung.HelloWorld.
Now, when we created com.baeldung package, we actually created this folder structure:
com/baeldung/HelloWorld.java
First, let’s try to run our program from the com/baeldung directory:
$ java com.baeldung.HelloWorld
Error: Could not find or load main class com.baeldung.HelloWorld
Still, we are not able to run our program.
Here, when we specified the fully qualified class name com.baeldung.HelloWorld, Java tried to find the HelloWorld.class file in com/baeldung, under the directory from where we were running the program.
As we were already inside com/baeldung, Java failed to find and run the HelloWorld program.
Now let’s move back to the parent folder and run it:
$ java com.baeldung.HelloWorld
Hello world..!!!
And we are again able to say “Hello” to the world.
5. Invalid Classpath
Before going ahead, let’s first understand what the classpath is. It’s the set of classes available to our currently running JVM.
We use the classpath variable to tell the JVM where to find the .class files on the file system.
While running a program, we can provide the classpath using -classpath option:
java -classpath /my_programs/compiled_classes HelloWorld
Here, Java will look for the HelloWorld.class file in /my_programs/compiled_classes folder, a folder whose name we just made up. By default, the classpath variable is set to “.”, meaning the current directory.
In the above section, we changed our directory to run our program. But what if we want to run it from some other folder? That’s when the classpath variable helps us.
To run our program from the directory com/baeldung, we can simply state that our classpath is two directories up — one for each package part:
$ java -claspath ../../ com.baeldung.HelloWorld
Hello world..!!!
Here, “..” represents the parent directory. In our case “../../” represents the top of our package hierarchy.
6. Conclusion
In this article, we learned the probable reasons for the error “Could not find or load main class.”
Then, of course, we also learned how to solve this error.
Автор оригинала: baeldung.
1. введение
Иногда, когда мы запускаем программу Java, мы можем увидеть “Не удалось найти или загрузить основной класс”. Легко догадаться о причине: JVM не смогла найти основной класс и выдала эту ошибку. Но почему бы и нет?
Дальнейшее чтение:
Как исправить java.lang.UnsupportedClassVersionError
Объясненный метод Java main()
В этом уроке мы обсудим вероятные причины неудачного поиска основного класса. Кроме того, мы посмотрим, как их исправить.
2. Пример Программы
Мы начнем с Hello World программы:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world..!!!"); } }
Теперь давайте скомпилируем его:
Здесь компилятор сгенерирует файл .class для нашей программы. Этот файл .class будет создан в том же каталоге. Файл .class будет иметь то же имя, что и имя класса, заданное в программе Java. Этот файл .class является исполняемым.
В следующих разделах мы запустим этот файл .class и попытаемся понять вероятные причины ошибки “Не удалось найти или загрузить основной класс”.
3. Неправильное Название Класса
Чтобы запустить файл .class , сгенерированный компилятором Java, мы можем использовать следующую команду:
А теперь давайте запустим нашу программу:
$ java helloworld Error: Could not find or load main class helloworld
Да, он потерпел неудачу с ошибкой “Не удалось найти или загрузить основной класс helloworld”.
Как обсуждалось ранее, компилятор сгенерирует файл .class с тем же именем, что и класс Java в программе . Таким образом, в нашем случае основной класс будет иметь имя Hello World , а не hello world .
Давайте попробуем еще раз с правильным корпусом:
$ java HelloWorld Hello world..!!!
На этот раз все прошло успешно.
3.1. Расширение файла
Чтобы скомпилировать программу на Java, мы должны указать имя файла с его расширением (. java ):
Но чтобы запустить . class file, нам нужно указать имя класса, а не имя файла. Таким образом, нет необходимости предоставлять расширение .class :
$ java HelloWorld.class Error: Could not find or load main class HelloWorld.class
Итак, опять же, давайте запустим нашу программу, используя правильное имя класса:
$ java HelloWorld Hello world..!!!
4. Имена пакетов Java
В Java мы сохраняем подобные классы вместе в том, что мы называем пакетом /.
Давайте переместим класс HelloWorld в пакет com.baeldung :
package com.baeldung; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world..!!!"); } }
Теперь давайте скомпилируем и запустим обновленную программу Hello World , как и раньше:
$ java HelloWorld Error: Could not find or load main class HelloWorld
Но снова мы получаем ошибку “Не удалось найти или загрузить основной класс HelloWorld”!
Давайте попробуем понять, что же мы здесь упустили.
Чтобы запустить класс Java, который находится в пакете, мы должны указать его полное имя . Поэтому в нашем случае Hello World полное имя com.baeldung.Адский мир .
Теперь, когда мы создали com.baeldung package, мы фактически создали структуру папок, такую как:
com/baeldung/HelloWorld.java
Во-первых, давайте попробуем запустить нашу программу из каталога com/baeldung :
$ java com.baeldung.HelloWorld Error: Could not find or load main class com.baeldung.HelloWorld
Тем не менее, мы не можем запустить нашу программу.
Здесь, когда мы указали полное имя класса com.baeldung.HelloWorld , Java пытался найти HelloWorld.class файл в com/baeldung , в каталоге, из которого мы запускали программу.
Поскольку мы уже находились внутри com/baeldung , Java не смогла найти и запустить программу HelloWorld .
Теперь давайте вернемся в родительскую папку и запустим ее:
$ java com.baeldung.HelloWorld Hello world..!!!
Да, мы снова можем сказать “Привет” миру.
5. Недопустимый путь к классу
Прежде чем продолжить, давайте сначала разберемся, что такое путь к классам – это набор классов, доступных для нашей текущей JVM.
Мы используем переменную classpath, чтобы указать JVM, где найти файлы .class в файловой системе.
Во время выполнения программы мы можем указать путь к классу, используя параметр -classpath . пример:
java -classpath /my_programs/compiled_classes HelloWorld
Здесь Java будет искать HelloWorld.class файл в/ my_programs/compiled_classes папке, имя которой мы только что придумали. По умолчанию переменная пути к классу имеет значение”.”, что означает текущий каталог.
В приведенном выше разделе мы изменили наш каталог для запуска нашей программы. Но что, если мы захотим запустить его из какой-то другой папки? Вот когда переменная classpath помогает нам.
Чтобы запустить нашу программу из каталога com/baeldung , мы можем просто указать, что наш путь к классу состоит из двух каталогов – по одному для каждой части пакета:
$ java -claspath ../../ com.baeldung.HelloWorld Hello world..!!!
Здесь “..” представляет родительский каталог. В нашем случае “../../” представляет собой вершину иерархии пакетов.
6. Заключение
В этом уроке мы узнали вероятные причины ошибки “Не удалось найти или загрузить основной класс”.
Затем, конечно, мы также узнали, как решить эту ошибку.
The Java “Could not find or load main class” error is thrown when the JVM fails to find or load the main class while executing a program. It usually occurs when executing a Java program from the command line.
Install the Java SDK to identify and fix these errors
What Causes Error: Could not find or load main class
The «Could not find or load main class» error occurs when the JVM fails to load the main class. This can happen due to various reasons, such as:
- The class being declared in the incorrect package.
- The file path of the class not matching the fully qualified name.
- Incorrectly specified classpath of the application.
- Missing dependencies from the classpath.
- Incorrect directory path on the classpath.
- A typo in the class name.
Error: Could not find or load main class Example
Here’s an example of the Java «Could not find or load main class» error thrown when an incorrect class name is specified during execution:
Here’s an example Java class MyClass.java
:
public class MyClass {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Now the above class is compiled using the command line:
$ javac MyClass.java
The compiler generates an executable .class file for MyClass:
$ ls
MyClass.class MyClass.java
Now if the java
command is used to execute the .class file with an incorrect name, the «Could not find or load main class» error is thrown:
$ java Myclass
Error: Could not find or load main class Myclass
The generated .class file has the exact same name as the Java class, which in this case is MyClass.class
. Specifying the correct name will execute the program successfully:
$ java MyClass
Hello World
How to Fix Error: Could not find or load main class
There are several ways the «Could not find or load main class» error can occur while executing Java programs. Most of the time, it occurs because of specifying an incorrect class name, class file extension, file path or classpath.
The following tips can be useful to resolve the «Could not find or load main class» error:
- Using correct class name — The spelling and casing of the class name should be checked when executing the program.
- Using the class name without the .class extension — The
java
command expects the class name for executing the program, without the .class extension. Therefore, the following syntax should be used to execute Java classes: java <classname> - Using the correct file path — The path to the .class file should be checked and corrected if the error occurs. Remember to use the fully qualified name of the class that is in a package if executing it from outside the directory structure of the package.
- Correct classpath definition — The classpath should be checked and defined correctly if the error comes up. It can also be specified using the
java -cp
or-classpath
command line arguments.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!