Problem in playing an MP3 file in JavaFX - compatibility issue? - javafx

I'm trying to play a small MP3 file or two using JavaFX, trying with MediaPlayer and AudioClip but getting an exception in each case. Some kind of compatibility issue?
Technology stack (1) Windows 10 home (2) Java 8 update 211 (3) Java SE Development kit 13.0.1 (4) JavaFX 11.0.2.
Exception reported :
(1) MediaPlayer (when I create a new Media object)
Exception in thread "JavaFX Application Thread" java.lang.IllegalAccessError: class com.sun.media.jfxmediaimpl.NativeMediaManager (in unnamed module #0x30696d74) cannot access class com.sun.glass.utils.NativeLibLoader (in module javafx.graphics) because module javafx.graphics does not export com.sun.glass.utils to unnamed module #0x30696d74
(2) AudioClip (when I create a new AudioClip object)
Exception in thread "JavaFX Application Thread" java.lang.IllegalAccessError: class com.sun.media.jfxmediaimpl.NativeMediaManager (in unnamed module #0x403bc23b) cannot access class com.sun.glass.utils.NativeLibLoader (in module javafx.graphics) because module javafx.graphics does not export com.sun.glass.utils to unnamed module #0x403bc23b
Code listing :
// play a sound clip using Media
private void playMedia1() {
fullFileName = "short.mp3";
if (checkFileExists(fullFileName)) {
File f = new File(fullFileName);
System.out.println("File URI : " + f.toURI().toString());
Media media = new Media(f.toURI().toString());
MediaPlayer mplayer = new MediaPlayer(media);
mplayer.setAutoPlay(true);
} else {
System.out.printf("File %s not found%n", fullFileName);
}
}
// play a sound clip using AudioClip
private void playMedia2() {
fullFileName = "short.mp3";
if (checkFileExists(fullFileName)) {
File f = new File(fullFileName);
System.out.println("File URI : " + f.toURI().toString());
AudioClip clip1 = new AudioClip(f.toURI().toString());
clip1.play();
} else {
System.out.printf("File %s not found%n", fullFileName);
}
}
// test we can open the specified file
private boolean checkFileExists(String filename) {
File f = new File(filename);
return f.exists();
}

Related

After opening multiple web pages many times, freezing often occurs

I am developing a web crawler that will frequently request new web pages. During the testing process, the program often freezes.
I've written a test case that explains my usage and the scenario where the problem has occurred.
Sometimes, when it open a web page for 10 times, it may get stuck when it open it for 20 times. How many times do it open the web page, i are not sure.
using CefSharp;
using CefSharp.WinForms;
using System;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
ChromiumWebBrowser browser;
System.Timers.Timer timer;
int i = 1;
public Form1()
{
InitializeComponent();
timer = new System.Timers.Timer(400) { AutoReset = true };//Timer, automatically open a new web page
timer.Elapsed += Timer_Elapsed;
browser = new ChromiumWebBrowser("www.baidu.com") { Parent = splitContainer1.Panel1, Dock = DockStyle.Fill };
browser.LifeSpanHandler = new LifeSpanHandler(splitContainer1.Panel2);
browser.FrameLoadEnd += Browser_FrameLoadEnd;
}
private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
if (e.Frame.IsMain == false) return;
timer.Start();
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
i = i > 1 ? 1 : i + 1;
browser.ExecuteScriptAsync("document.getElementsByClassName('mnav c-font-normal c-color-t')[" + (i) + "].click()");//Open a link in the web page
}
}
class LifeSpanHandler : ILifeSpanHandler
{
Control host;
internal LifeSpanHandler(Control host)
{
this.host = host;
}
public bool DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
{
return false;
}
public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser)
{
}
public void OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
{
}
public bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
{
newBrowser = null;
var webBrowser = (ChromiumWebBrowser)chromiumWebBrowser;
webBrowser.Invoke(new Action(() =>
{
if (host.HasChildren) host.Controls[0].Dispose();
var control = new Control { Parent = host, Dock = DockStyle.Fill };
control.CreateControl();
windowInfo.SetAsChild(control.Handle);
}));
return false;
}
}
}
The test code is placed on GitHub, which is the visual studio 2019 project. We hope you can execute the project locally, so as to find problems more intuitively. Thank you very much.
https://github.com/haohaodz/cefsharp-form-vs2019-problem.git
Have you tested with other websites?
High frequency of requests to other websites can also lead to deadlock.
Does the problem reproduce with github.com/cefsharp/CefSharp.MinimalExample
the problem does not reproduce with github.com/cefsharp/CefSharp.MinimalExample.
in BrowserTabUserControl.cs
browser.LifeSpanHandler = new LifeSpanHandler(openPopupsAsTabs: false);
It opens a web page in a new window by default.High frequency of open multiple web pages, the freezing problem does not reproduce.
I change openPopupsAsTabs to true and open a new page in tabs
browser.LifeSpanHandler = new LifeSpanHandler(openPopupsAsTabs: true);
High frequency of open multiple web pages, the program will freezes.
The program freezes in the dispose method:
System.Windows.Forms .dll! System.Windows.Forms . UnsafeNativeMethods.DestroyWindow (
System.Runtime.InteropServices . handleref hWnd) unknown
System.Windows.Forms .dll! System.Windows.Forms . NativeWindow.DestroyHandle () unknown
System.Windows.Forms .dll! System.Windows.Forms . Control.DestroyHandle () unknown
System.Windows.Forms .dll! System.Windows.Forms . Control.Dispose (bool disposing) unknown
System.dll ! System.ComponentModel.Component . dispose() unknown
Sometimes the program exits suddenly,There is an exception:
Exception thrown:“ System.IO.PipeException ”(located at System.ServiceModel.dll (2)
Exception thrown:“ System.ServiceModel.CommunicationException ”(located at System.ServiceModel.dll (2)
Exception thrown:“ System.ServiceModel.CommunicationException ”(located at System.ServiceModel.dll (2)
Exception thrown:“ System.ServiceModel.CommunicationException ”(located at System.ServiceModel.dll (2)
Exception thrown:“ System.ServiceModel.CommunicationException ”(located at System.ServiceModel.Internals . DLL)
Exception thrown:“ System.ServiceModel.CommunicationException ”(located at System.ServiceModel.Internals . DLL)
Exception thrown:“ System.ServiceModel.CommunicationObjectFaultedException ”(located at System.ServiceModel.dll (2)

javafx error even though url is correct

Even though the path given is correct & image is displaying in scene builder, it is throwing error while running the application.
Executing C:\Users\433240\Documents\NetBeansProjects\UI\dist\run547088191\UI.jar using platform C:\Program Files (x86)\Java\jdk1.8.0_40\jre/bin/java
Device "Intel(R) G41 Express Chipset" (\\.\DISPLAY1) initialization failed :
WARNING: bad driver version detected, device disabled. Please update your driver to at least version 8.15.10.2302
null/Images/home.png
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1091)
... 23 more
Exception running application ui.Main
Java Result: 1
I had the same problem
Solution:
go to java controller class and write this code
private Image image;
#FXML
ImageView imageview; // type your imageview fixid
private void setImage(String url) {
try {
image = new Image(url);
imageview.setImage(image);
} catch (Exception e) {
System.out.println(e);
}
}

Error while running client code in EJB

Getting error while running client code in EJB:
Exception in thread "Main Thread" java.lang.NoClassDefFoundError:
weblogic/kernel/KernelStatus at
weblogic.jndi.Environment.(Environment.java:78) at
weblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFactory.java:117)
at
javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
at
javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223) at
javax.naming.InitialContext.(InitialContext.java:197) at
User.main(User.java:21)
I added wlfullclient.jar, server's Remote interface jar, also I saw article in which I saw to add wlclient.jar and weblogic.jar but then also got same error.
Help highly appreciated.
Client code:
import com.amdocs.Stateful.*;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class User
{
public static void main(String args[]){
Hashtable<String,String> ht = new Hashtable<String,String>();
ht.put(InitialContext.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");// you have to start from root location to search for JNDI tree
//JNDI registry tree is normally maintained as Binary tree, JNDi is normally binary tree which have root node at top
ht.put(InitialContext.PROVIDER_URL,"t3://localhost:7001"); // address of registry
try{
System.out.println("Hello");
InitialContext ic = new InitialContext(ht); // start searching wrt what we set in ht , it's constructor takes HashTable only
System.out.println("Hello2");
MyCartRemote ref=(MyCartRemote)ic.lookup("MyCartBeanJNDI#com.amdocs.Stateful.MyCartRemote");
ref.add("Hi");
ref.add("Jeetendra");
MyCartRemote ref1=(MyCartRemote)ic.lookup("MyCartBeanJNDI#com.amdocs.Stateful.MyCartRemote");
ref1.add("Hi");
ref1.add("Subhash");
ref1.add("Ghai");
System.out.println("Object 1 data: "+ref.show());
System.out.println("Object 2 data: "+ref1.show());
}
catch (NamingException e){ e.printStackTrace(); }
}
}
Try removing WebLogic System Libraries from the Bootstrap Entries section. It worked for me when i got the same error.

Error loading fxml files from a folder other than the bin folder

I am a fairly new java programmer. I only have about five weeks of experience, starting from zero, and I am having problems getting javafx fxml files created in Scene Builder to load correctly if they are not in the same folder as the controller classes.
I am using
Win7x64 running jre7x86 for this build
Eclipse Juno Service Release 1
Build id: 20120920-0800
jre version 1.7.0_07
javaFx version 2.2.1-b03
SceneBuilder version 1.0-b50
My scene loader code is
private static final String RESOURCE_PATH = "/resources/";
public static Stage buildStage(#SuppressWarnings("rawtypes") Class pClass,
String stageTitle, String resourceLocation)
{
Stage temp = new Stage();
Pane page = null;
try
{
page = FXMLLoader.load(pClass.getResource(RESOURCE_PATH + resourceLocation), null,
new JavaFXBuilderFactory());
}
catch (IOException e)
{
e.printStackTrace();
}
Scene scene = new Scene(page);
temp.setScene(scene);
temp.setTitle(stageTitle);
temp.setResizable(false);
return temp;
}
I know that the project directory is the /workspace/projectName/ so theoretically the loader should be able to find the files if it's given a relative path right? The error I'm getting is
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException: Location is required.
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2737)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2721)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2707)
at outofunit.system.StageFactory.buildStage(StageFactory.java:32)
at outofunit.desktop.ArcMaster.start(ArcMaster.java:28)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:206)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
... 1 more
I've tried giving the loader an absolute path as well but it just isn't accepting anything that isn't directly in the same directory. I'm grasping at straws here trying to figure this out.
I've tried to research this on my own but I haven't gotten much, the few answers on here that seemed similar didn't seem to help, that or I am too dense and/or inexperienced to make sense of them. They are JavaFX 2.0 loading fxml files with event handlers fails and JavaFX 2.0 FXML resource loading error
A buddy of mine was able to overcome this problem by using this code
public void load(String pFileName, Stage pStage, String pTitle)
{
String fName = RESOURCE_PATH + pFileName;
try
{
String externalForm = getClass().getResource(fName)
.toExternalForm();
InputStream inStream = new URL(externalForm).openStream();
FXMLLoader loader = new FXMLLoader();
Pane p = (Pane)loader.load(inStream);
pStage.setTitle(pTitle);
pStage.setScene(new Scene(p));
mWindowControl = loader.getController();
mWindowControl.setUp(pStage);
pStage.show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
The biggest difference and the reason why I haven't been using his code is because my root pane is an Anchor pane instead of a normal pane, and his way URL instream forces a normal pane. Am I at fault for not using a normal pane as my base? I would love any help or input you guys can give. Thank you.
Edit: So I've been working on this problem and the error message has changed.
I changed the code to this
private final String RESOURCE_PATH = "resources/";
public void load(String pFileName, Stage pStage, String pTitle)
{
String fName = RESOURCE_PATH + pFileName;
Pane page = null;
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(fName));
try
{
page = (Pane) fxmlLoader.load();
}
catch (IOException exception)
{
throw new RuntimeException(exception);
}
Scene scene = new Scene(page);
pStage.setScene(scene);
pStage.setTitle(pTitle);
mWindowControl = fxmlLoader.getController();
mWindowControl.setUp(pStage);
pStage.show();
}
but the error I'm now getting is
java.lang.IllegalStateException: Location is not set.
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2021)
at outofunit.desktop.WindowLoader.load(WindowLoader.java:136)
at outofunit.desktop.WindowLoader.load(WindowLoader.java:62)
at outofunit.desktop.ArcMaster.start(ArcMaster.java:30)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:206)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
at java.lang.Thread.run(Unknown Source)
I don't understand how the location is not being set
It's a path issue, java needs to know where to get the file from the package hierarchy.
So using "/package1/resourcename.fxml" should find the source from the root of the tree.
You normally leave off the "/" at the start as you are already at the top of the package tree.
Both exceptions say "the (FXML) file you are trying to load cannot be found in the location you have provided". Your filename is wrong or its path. Give your package structure or at least the path of class file that includes load(String pFileName, Stage pStage, String pTitle) method and the path of FXML file you want to load. Read the javadoc API of getResource() and examine sample codes about it on the net.

Create path from path value?

Can i create a Path using its value??
Path p=new Path();
p.getElements().add(new MoveTo(mouse.getX(), mouse.getY()));
System.out.Print(p);
This will print
Path#29f12030
can i convert this into path again?
You have already created a path and it's still a path, you don't need to convert it.
When you call System.out.print(p) you invoke the default toString function on your p object, which prints an internal Java reference to your Path (e.g. Path#29f12030).
If you override the default toString method with your own implementation, as is shown in the sample below, your print statement will display the value of the path.
public class PrintPath extends Application {
public static void main(String[] args) throws Exception { launch(args); }
#Override public void start(final Stage stage) throws Exception {
Path p = new PrintedPath();
p.getElements().add(new MoveTo(100, 150));
System.out.println(p);
stage.setScene(new Scene(new StackPane()));
stage.show();
}
class PrintedPath extends Path {
#Override public String toString() {
StringBuilder b = new StringBuilder();
for (PathElement e: getElements()) {
if (e instanceof MoveTo) {
MoveTo m = (MoveTo) e;
b.append("M").append(m.getX()).append(" ").append(m.getY()).append(" ");
}
// logic to display other path element types could be added here . . .
}
return "Path{ " + b.toString() + "}";
}
}
}
I think you should elaborate your purpose of sending data over network in a context of your app architecture. Give some fundamental details about it. In my understanding, you want to send a Path instance over the network and able to process it on the other end. If so,
- have a look to a serialization API. Read the post about it "How to transfer objects over network using java". Extend the Path or wrap it into another class then implement Serializable.
- Or, refer to Java Architecture for XML Binding (JAXB). Basically by using it you can convert/marshal the objects to XML strings and transfer over the network and then unmarshal it. Here is hello world example.
- Or, implement your own encoding/decoding mechanism to transfer the Path object.

Resources