UIDefaults.getUI() failed: error when loading a JFrame into another project - java

I found this project which works just fine in a standalone run. However when I try to add it to a JPanel in another project (already did this in the exact same project but with a JFrame of my own and worked fine) this error arises:
UIDefaults.getUI() failed: no ComponentUI class for: doubleslider.MThumbSlider[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=,isInverted=false,majorTickSpacing=0,minorTickSpacing=0,orientation=HORIZONTAL,paintLabels=false,paintTicks=false,paintTrack=true,snapToTicks=false,snapToValue=true]
java.lang.Error
at javax.swing.UIDefaults.getUIError(UIDefaults.java:729)
at javax.swing.MultiUIDefaults.getUIError(MultiUIDefaults.java:130)
at javax.swing.UIDefaults.getUI(UIDefaults.java:759)
at javax.swing.UIManager.getUI(UIManager.java:1002)
at javax.swing.JSlider.updateUI(JSlider.java:323)
at doubleslider.MThumbSlider.updateUI(MThumbSlider.java:44)
at javax.swing.JSlider.<init>(JSlider.java:275)
at javax.swing.JSlider.<init>(JSlider.java:182)
at doubleslider.MThumbSlider.<init>(MThumbSlider.java:24)
at doubleslider.DoubleSlider.<init>(DoubleSlider.java:29)
at com.einge.scadaremotecontrol.Ventana.<init>(Ventana.java:227)
at com.einge.scadaremotecontrol.ScadaRemoteControl.<init>(ScadaRemoteControl.java:92)
at com.einge.scadaremotecontrol.ScadaRemoteControl.main(ScadaRemoteControl.java:197)
UIDefaults.getUI() failed: no ComponentUI class for: doubleslider.MThumbSlider[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=,isInverted=false,majorTickSpacing=0,minorTickSpacing=0,orientation=HORIZONTAL,paintLabels=false,paintTicks=false,paintTrack=true,snapToTicks=false,snapToValue=true]
java.lang.Error
at javax.swing.UIDefaults.getUIError(UIDefaults.java:729)
at javax.swing.MultiUIDefaults.getUIError(MultiUIDefaults.java:130)
at javax.swing.UIDefaults.getUI(UIDefaults.java:759)
at javax.swing.UIManager.getUI(UIManager.java:1002)
at javax.swing.JSlider.updateUI(JSlider.java:323)
at doubleslider.MThumbSlider.updateUI(MThumbSlider.java:44)
at doubleslider.MThumbSlider.<init>(MThumbSlider.java:26)
at doubleslider.DoubleSlider.<init>(DoubleSlider.java:29)
at com.einge.scadaremotecontrol.Ventana.<init>(Ventana.java:227)
at com.einge.scadaremotecontrol.ScadaRemoteControl.<init>(ScadaRemoteControl.java:92)
at com.einge.scadaremotecontrol.ScadaRemoteControl.main(ScadaRemoteControl.java:197)
My first guess is that the MultiTumbSlider class is trying to set a different Look&Feel than my JFrame. Any solutions? I couldn't figure this out and I really need two sliders so to have a time Range
Any help will be appretiated!

I don't recognize the loading approach used in this very old example; it appear to be based on the current Look & Feel. You might try setting javax.swing.plaf.metal.MetalLookAndFeel explicitly. Going forward, look at Kirill Grouchnikov's How to Write a Custom Swing Component for guidance on modernizing the delegate plumbing.

At the book "Java Swing, 2nd Edition", by Marc Loy et. al., at the section "Creating Your Own Component" (Chapter 28: Swing Under the Hood), we have the code line at the main() method:
UIManager.put(JogShuttleUI.UI_CLASS_ID, "BasicJogShuttleUI");
This will inform the UIDefaults, through UIManeger, the class name of the basic UI delegate of the custom component. Note, however, that you must provide the fully qualified class name, since it will be located by the class loading mechanism.
For example, when I'm use
UIManager.put(DiagramUI.UI_CLASS_ID, "BasicDiagramUI");
I get the same error reported by your question. But, when I change it to
UIManager.put(DiagramUI.UI_CLASS_ID, BasicDiagramUI.class.getName());
Things works pretty well. Nice coding!

Related

ServiceLoader cannot find service loaded from path

I have been trying to do a kind of plugin-system using the ServiceLoader. There are 2 modules, the first provides the abstract class LoadedRealmPlugin. The second one extends this class. I have added the file corresponding to the full name of the ServiceProvider and added the service-class to it. IntelliJ does not find any errors (but when changing the filename or classname it does). Here is the structure:
MainModule
src
main
java
com.interestingcompany.mainmodule
LoadedRealmPlugin
MainModule.iml
Plugin
META-INF
services
com.interestingcompany.mainmodule (-> Content: "PluginExtension")
src
PluginExtension
Plugin.iml
(This is simplified, I left out classes that (I think) are not important to the ServiceLoader. I can post a screenshot of the actual structure if anyone needs it)
Here is the code I use to load the Service:
File file = new File("Plugins/Plugin.jar");
URLClassLoader c = new URLClassLoader(new URL[]{file.getAbsoluteFile().toURI().toURL()});
ServiceLoader<LoadedRealmPlugin> loader = ServiceLoader.load(LoadedRealmPlugin.class, c);
LoadedRealmPlugin p = loader.iterator().next(); // Throws a java.util.NoSuchElementException
p.Initialize(RealmPath); // Abstract method implemented in the service
return p;
When trying to run it, I always get an empty ServiceLoader. I looked at this post, but I was not quite sure about how to apply that answer since I am trying to load my plugin from a file. In addition, I found this post. Yet, there was no answer, just some comments that did not seem to have answered the question.
As you might have been able to tell, this is my first time working with classloaders. If there is any additional information needed, just ask me. Thank you for reading through my beginner troubles.
package-less classes are in the unnamed package, which is inaccessible to rather a lot of code, notably including here.
Put PluginExtension.java in a package, make sure the content of your META-INF/services/com.ic.mainmodule file reflects this (content should be pkg.PluginExtension), and it'll work fine.

No Main class found in NetBeans

I have been working on an assignment for my class in programming. I am working with NetBeans. I finished my project and it worked fine. I am getting a message that says "No main class found" when I try to run it. Here is some of the code with the main:
package luisrp3;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
I posted this before but had a couple issues. i have fixed the others and now have just this one remaining. Any advice will be greatly appreciated.
Right click on your Project in the project explorer
Click on properties
Click on Run
Make sure your Main Class is the one you want to be the entry point. (Make sure to use the fully qualified name i.e. mypackage.MyClass)
Click OK.
Run Project :)
If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)
Also, for others out there with a slightly different problem where Netbeans will not find the class when you want when doing a browse from "main classes dialog window".
It could be that your main method does have the proper signature. In my case I forgot the args.
example:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above.
Args: You can name the argument anything you want, but most programmers choose "args" or "argv".
Read more here:
http://docs.oracle.com/javase/tutorial/getStarted/application/
When creating a new project - Maven - Java application in Netbeans
the IDE is not recognizing the Main class on 1st class entry. (in Step 8 below we see no classes).
When first a generic class is created and then the Main class is created Netbeans is registering the Main class and the app could be run and debugged.
Steps that worked for me:
Create new project - Maven - Java application
(project created: mytest; package created: com.me.test)
Right-click package: com.me.test
New > Java Class > Named it 'Whatever' you want
Right-click package: com.me.test
New > Java Main Class > named it: 'Main' (must be 'Main')
Right click on Project mytest
Click on Properties
Click on Run > next to 'Main Class' text box: > Browse
You should see: com.me.test.Main
Select it and click "Select Main Class"
Hope this works for others as well.
The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class: box until you see the connections. (Note that the class containing the main method need not necessarily be named Main but the main method can have no other name.)
I had the same problem in Eclipse, so maybe what I did to resolve it can help you.
In the project properties I had to set the launch configurations to the file that contains the main-method (I don't know why it wasn't set to the right file automatically).
In project properties, under the run tab, specify your main class.
Moreover, To avoid this issue, you need to check "Create main class" during creating new project. Specifying main class in properties should always work, but if in some rare case it doesn't work, then the issue could be resolved by re-creating the project and not forgetting to check "Create main class" if it is unchecked.
If the advice to add the closing braces work, I suggest adding indentation to your code so every closing brace is on a spaced separately, i.e.:
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
// stuff
}
}
This just helps with readability.
If, on the other hand, you just forgot to copy the closing braces in your code, or the above suggestion doesn't work: open up the configuration and see if you can manually set the main class. I'm afraid I haven't used NetBeans much, so I can't help you with where that option is. My best guess is under "Run Configuration", or something like that.
Edit: See peeskillet's answer if adding closing braces doesn't work.
There could be a couple of things going wrong in this situation (assuming that you had code after your example and didn't just leave your code unbracketed).
First off, if you are running your entire project and not just the current file, make sure your project is the main project and the main class of the project is set to the correct file.
Otherwise, I have seen classmates with their code being fine but they still had this same problem. Sometimes, in Netbeans, a simple fix is to:
Copy your current code (or back it up in a different location)
Delete your current file
Create a new main class in your project (you can name it the old one)
Paste your code back in
If this doesn't work then try to clear the Netbeans cache, and if all else fails, then just do a clean un-installation and re-installation of Netbeans.
In the toolbar search for press the arrow and select Customize...
It will open project properties.In the categories select RUN.
Look for Main Class.
Clear all the Main Class character and type your class name.
Click on OK.
And run again.
The problem is solved.
If that is all your code, you forgot to close the main method.
Everything else looks good to me.
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
}}
Try that.
You need to add }} to the end of your code.
You need to rename your main class to Main, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main.
That's all.
import java.util.Scanner;
public class FarenheitToCelsius{
public static void main(String[]args){
Scanner input= new Scanner(System.in);
System.out.println("Enter Degree in Farenheit:");
double Farenheit=input.nextDouble();
//convert farenheit to celsius
double celsuis=(5.0/9)*(farenheit 32);
system.out.println("Farenheit"+farenheit+"is"+celsius+"in celsius")
{
I also experienced Netbeans complaining to me about "No main classes found". The issue was on a project I knew worked in the past, but failed when I tried it on another pc.
My specific failure reasons probably differ from the OP, but I'll still share what I learnt on the debugging journey, in-case these insights help anybody figure out their own unique issues relating to this topic.
What I learnt is that upon starting NetBeans, it should perform a step called "Scanning projects..."
Prior to this phase, you should notice that any .java file you have with a main() method within it will show up in the 'Projects' pane with its icon looking like this (no arrow):
After this scanning phase finishes, if a main() method was discovered within the file, that file's icon will change to this (with arrow):
So on my system, it appeared this "Scanning projects..." step was failing, and instead would be stuck on an "Opening Projects" step.
I also noticed a little red icon in the bottom-right corner which hinted at the issue ailing me:
Unexpected Exception
java.lang.ExceptionInInitializerError
Clicking on that link showed me more details of the error:
java.security.NoSuchAlgorithmException: MD5 MessageDigest not available
at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
at java.security.Security.getImpl(Security.java:695)
at java.security.MessageDigest.getInstance(MessageDigest.java:167)
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:113)
Caused: java.lang.RuntimeException
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:115)
Caused: java.lang.ExceptionInInitializerError
at org.netbeans.modules.parsing.lucene.LuceneIndex$DirCache.createFSDirectory(LuceneIndex.java:839)
That mention of "java.security" reminded me that I had fiddled with this machine's "java.security" file (to be specific, I was performing Salvador Valencia's steps from this thread, but did it incorrectly and broke "java.security" in the process :))
Once I repaired the damage I caused to my "java.security" file, NetBeans' "Scanning projects..." step started to work again, the little green arrows appeared on my files once more and I no longer got that "No main classes found" issue.
Had the same problem after opening a project that I had downloaded in NetBeans.
What worked for me is to right-click on the project in the Projects pane, then selecting Clean and Build from the drop-down menu.
After doing that I ran the project and it worked.
Make sure the access modifier is public and not private. I keep having this problem and always that's my issue.
public static void main(String[] args)

Load Custom Fonts in JavaFX + Clojure

As background, I realize there are about 5 other posts on Stack Overflow about this, bur I've looked at the responses and researched this for countless hours with no real solution. Otherwise I wouldn't have posted here.
I'm new to JavaFX, and I like Clojure, so I'm using chrisx's clj-javafx project from Github as a Clojure wrapper for JavaFX. Most operations work great, such as placing components on the scene/stage and styling them with CSS. There's just one issue: I want to import a custom font, and so far I haven't been able to.
I've tried multiple methods. The Java version of the first thing I tried is:
Font.loadFont(<myClass>.class.getResource("mpsesb.ttf").toExternalForm(), 14);
I tried to do that in Clojure using Java interop but I'm not sure how Clojure handles Java classes. Instead I used clojure.java.io.resource:
(use '[clojure.java.io :only [resource]])
(resource "mpsesb.tff")
And it prints the URL of the .ttf file just fine.
Then I tried to use that URL and use it as a parameter in the Font.loadFont method, which didn't work. After playing around with seriously 100 permutations of dot operators and Java methods and classes, I got the following to not print any errors, unlike the other combinations I tried:
(Font/loadFont "fonts/ttf/mpsesb.ttf")
But it just returns nil, which according to the JavaFX API means the font didn't actually load. I even tried fake pathnames and they also returned nil without errors, so the Font/loadFont function seems less promising than I thought.
I finally tried using CSS to load the font instead of using Java to import it:
#font-face {
font-family: 'MyrProSemiExtBold';
src: url('file:/Users/<restOfPath>/mpsesb.ttf');
}
.label {
-fx-font-size: 14px;
-fx-font-weight: normal;
-fx-font-family: 'MyrProSemiExtBold';
}
But no luck. The labels just show up as the default font (Lucida Grande) at 14 pt.
Thank you ahead of time for any suggestions you may have.
EDIT:
Thanks, #jewelsea. The first thing I did after reading what you wrote is get Java 8 + JDK 8 (build b101). I'm using Sublime Text, so I got SublimeREPL to recognize JavaFX using Maven like so in Terminal:
$ mvn deploy:deploy-file -DgroupId=local.oracle -DartifactId=javafxrt -Dversion=8.0 -Dpackaging=jar -Dfile=/System/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home/jre/l‌​ib/ext/jfxrt.jar -Durl=file:/Users/vaniificat/.m2/repository
Most of the JavaFX-referent code worked, but now the whole javafx.scene.control package doesn't work, which means no Labels, no Buttons, no TextFields, etc.... :
> (import javafx.scene.control.Button)
: NoClassDefFoundError Could not initialize class javafx.scene.control.Button
java.lang.Class.forName0 (Class.java:-2)
> (import javafx.scene.control.Label)
: NoClassDefFoundError javafx.scene.control.Labeled
java.lang.Class.forName0 (Class.java:-2)
> (import javafx.scene.control.TextField)
: NoClassDefFoundError javafx.scene.control.Control
java.lang.Class.forName0 (Class.java:-2)
> (import '(javafx.scene.control Button Label PasswordField TextField))
: NoClassDefFoundError Could not initialize class javafx.scene.control.Button
java.lang.Class.forName0 (Class.java:-2)
A possible reference to these errors may be found at https://forums.oracle.com/thread/2526150. Basically the gist is that JavaFX 8 is only in beta so we can't expect it to work 100%. Hmm!
I opened an issue on JIRA: https://bugs.openjdk.java.net/browse/JDK-8093894. Once this gets addressed I can more fully explore #jewelsea 's other suggestions.
These are mostly suggestions rather than definitive solutions
On #font-face
Use Java 8 if you can. It has support for the #font-face css notation (which earlier versions of JavaFX such as 2.2 do not). It also has a revamped font system which might be a bit more robust. Because the font face can be loaded via css in Java 8, you may not need to solve your loading resources relative to the class location issue.
On Font.loadFont
You should be able to use the Font.loadFont method as you are trying to use it. JavaFX 2.x has supported custom fonts from it's initial release. There are some steps for loading fonts in JavaFX in plain Java: How to embed .ttf fonts is JavaFx 2.2?. I know you have already looked at that and it hasn't helped - just including it here for reference so that somebody who really knows clojure but not JavaFX may help to troublehoot the issue.
Check that your target font is compatible
Double-check that the particular font that you are using loads and is used in a regular Java based JavaFX application (just to ensure that there is not something incompatible between the font file and the JavaFX system on your platform).
You may need further help
I don't know how loading relative resources works in clojure either (or maybe there is some other issue with your code) - but perhaps a clojure expert can post another answer that allows it to work. You may want to edit your question to include an sscce.
Update: As was pointed out, the original answer did not directly answer the OP's question. I've created a blog post about the original technique in case anyone is interested.
Here is a short program that does what you want.
(ns demo.core
(:gen-class
:extends javafx.application.Application)
(:import
[javafx.application Application]
[javafx.event EventHandler]
[javafx.scene Scene]
[javafx.scene.control Button]
[javafx.scene.layout StackPane]
[javafx.scene.text Font])
(:require [clojure.java.io :as jio]))
(defn- get-font-from-resource
"Load the named font from a resource."
[font-name]
(let [prefix "demo/resources/"
url (jio/resource (str prefix font-name))
fnt (Font/loadFont (.toExternalForm url) 20.0)]
fnt))
(defn -start
"Build the application interface and start it up."
[this stage]
(let [root (StackPane.)
scene (Scene. root 600 400)
fnt (get-font-from-resource "ITCBLKAD.TTF")
btn (Button. "Press Me!")]
(.setOnAction btn
(reify EventHandler
(handle [this event]
(doto btn
(.setText (str "This is " (.getName fnt)))
(.setFont fnt)))))
(.add (.getChildren root) btn)
(doto stage
(.setTitle "Font Loading Demo")
(.setScene scene)
(.show))))
(defn -main
[& args]
(Application/launch demo.core args))
In this project, I placed the font file in resources, a sub-directory of demo - where the Clojure source is stored - hence the "prefix" in the function get-font-from-resource.
It looks like the problem you might have been having with loadFont was in your conversion from the URL to the String form. The external form is an absolute path starting at the root directory on the drive.
Tip: You probably know this, but one thing that continually screws me up are methods in JavaFX that require double parameters, like Font/loadFont. I'm used to Java just promoting integer arguments to double. In Clojure, if you use an integer where a double is required, the program fails with a less than useful error message.

JACOB get HWND of window

I'm looking to get the native Window handle of a powerpoint window using Java / JACOB. The MSDN documentation seems to suggest it should be possible to just grab the "HWND" property, so I'm attempting that like so:
app = new ActiveXComponent("PowerPoint.Application");
Dispatch presentations = app.getProperty("Presentations").toDispatch();
presentation = Dispatch.call(presentations, "Open", fileLocation).toDispatch();
EnumVariant windows = new EnumVariant(Dispatch.get(presentation, "Windows").toDispatch());
Dispatch window = windows.nextElement().toDispatch();
Dispatch.get(window, "HWND"); //Exception here
However, I don't seem to be able to get the window handle this way - I get the following error:
Exception in thread "main" com.jacob.com.ComFailException: A COM exception has been encountered:
At Invoke of: HWND
Description: 80020003 / Member not found.
at com.jacob.com.Dispatch.invokev(Native Method)
at com.jacob.com.Dispatch.invokev(Dispatch.java:625)
at com.jacob.com.Dispatch.get(Dispatch.java:788)
at tester.PowerpointSlideShowRunner.<init>(PowerpointSlideShowRunner.java:54)
at tester.PowerpointSlideShowRunner.main(PowerpointSlideShowRunner.java:154)
Is this a bug in the library, or am I doing something wrong / misunderstanding something here? The latter is quite possible as I'm entirely new to Jacob. Either way, how should I grab the HWND of the Powerpoint window using JACOB?
The MSDN documentation you have linked is for the .NET Interop assembly which wraps the PowerPoint COM object model for use by .NET managed code, rather than for the COM object model itself.
The metadata in the interop assembly shows that there is actually an undocumented HWND property present in the COM interface to a DocumentWindow, but it carries the special type library attribute FUNCFLAG_FRESTRICTED which indicates that it
is intended for system-level functions or functions that type browsers
should not display.
I imagine this is the reason that your attempt to call this property by name through the DocumentWindow dispatch interface is failing.
However, the Interop assembly metadata also shows that the DISPID (dispatch identifier) for this restricted property is the value 0x7e4. I'm not very familiar with the JACOB library but I believe there is an override which allows you to get the value of a property by DISPID rather than by name:
Dispatch.get(window, 0x7e4);
I suggest you give this a try.

Java Applet/Web Browser Issue

I am new to Java (and programming in general) so I thought that making a simple test case applet would help to form a basic understanding of the language.
So, I decided to make a basic applet that would display a green rectangle. The code looks like:
import javax.swing.JApplet;
import java.awt.Color;
import java.awt.Graphics;
public class Box extends JApplet{
public void paint(Graphics page){
page.setColor(Color.green);
page.fillRect(0,150,400,50);
}
}
The HTML file (test.html) that I then embedded that into looks like:
<html>
<body>
<applet code="Box", height="200" width="400">
</applet>
</body>
</html>
I then compiled/saved the Java bit, and put the two into the same folder. However, when I attempt to view the html file, all I see is an "Error. Click for details" box. I tested this in both the most current version of Fire Fox and Opera, and too did I make sure that the Java plug-in was enabled and up to date for both.
So what exactly am I forgetting to do here?
It seems as if everything is close to OK.
Once the .class file is in the same folder as your HTML file it should come up. Your code might contain a typos (comma after "Box").
Example :
<Applet Code="MyApplet.class" width=200 Height=100>
See also :
http://www.echoecho.com/applets01.htm
#Juser1167589 I hope your not still having issues with this, but if you are, try going into your program files, delete the JAVA folder, then redownload java from the big red button on 'java.com'. If there is no JAVA folder then * FACEPALM * GO DOWNLOAD JAVA. another possible answer to why you were seeing the errors on the other sites is that they might not have the required resources to run it anymore.
Applets are not a good place to start.
They are a very old technology and really not very widely used compared to other parts of the Java technology stack.
If you're new to programming in general, I really wouldn't start with applets.
Instead, you should try learning basic programming and Java by building some simple console apps. I've added some general comments about how to do this. After your confidence rises, you can then start worrying about adding extra complexity, applets etc.
First of all download an IDE. Eclipse is one obvious choice (there are also NetBeans and IntelliJ). All modern developers work within an IDE - don't be tempted to try to muddle through without one.
Then, you should have a "scratchpad" - a class where you can try out some simple language features. Here's one which might be useful:
package scratch.misc;
public class ScratchImpl {
private static ScratchImpl instance = null;
// Constructor
public ScratchImpl() {
super();
}
/*
* This is where your actual code will go
*/
private void run() {
}
/**
* #param args
*/
public static void main(String[] args) {
instance = new ScratchImpl();
instance.run();
}
}
To use this, save this as a .java file. It can be a template for other simple experiments with Java. If you want to experiment with a language feature (inheritance, or polymorphism, or collections or whatever you want to learn) - then copy the template (use the copy and rename features inside your IDE, rather than manually copying the file and changing the type names) to a new name for your experiment.
You may also find some of my answer here to be useful.

Categories