SWT window runnable on Linux but not on Mac - java

I added a SWT window to my project as
public class swtUI {
protected Shell shell;
protected Display display;
public static void launch() {
try {
swtUI window = new swtUI();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
public void open() {
display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
// create all controls
blablabal
}
}
and call it in main() as
public static void main(String[] args) {
swtUI.launch();
System.out.println("\nComplete");
}
No problem running on Linux.
But when I replace the linux swt.jar with maxos swt.jar and run on mac, I got exception:
***WARNING: Display must be created on main thread due to Cocoa restrictions.
org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.widgets.Display.error(Unknown Source)
at org.eclipse.swt.widgets.Display.createDisplay(Unknown Source)
at org.eclipse.swt.widgets.Display.create(Unknown Source)
at org.eclipse.swt.graphics.Device.<init>(Unknown Source)
at org.eclipse.swt.widgets.Display.<init>(Unknown Source)
at org.eclipse.swt.widgets.Display.<init>(Unknown Source)
at org.eclipse.swt.widgets.Display.getDefault(Unknown Source)
at edu.rockefeller.casanovaLab.csvCheck.CsvSuiteGUI.open(CsvSuiteGUI.java:129)
at edu.rockefeller.casanovaLab.csvCheck.CsvSuiteGUI.launch(CsvSuiteGUI.java:119)
at edu.rockefeller.casanovaLab.csvCheck.Program.main(Program.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
I am pretty new to SWT. How should I change my code to make it work on mac?
Thanks

Seems this is mentioned in this FAQ. From the same link:
To work around this problem you'll have to pass the -XstartOnFirstThread option to the java executable as follows:
java -XstartOnFirstThread -cp swt.jar:. ControlExample

Related

NoSuchElementException in Stack trace, tried some other solutions in the community still not helpful [duplicate]

This question already exists:
javaFX InvocagtionTargetException in eclipse [closed]
Closed 2 years ago.
Other possible solutions I got in different forums are not working. Here is my code.
class javaFX extends Application{
#Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("JavaFX app");
Label label = new Label("Hello World, JavaFX !");
Scene scene = new Scene(label, 400, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String args[]) {
Application.launch(args);
}
}
This is the StackTrace. It is showing NoSuchElementException which is a bit weird.
Exception in Application constructor
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class xlSheets.javaFX
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:907)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$159(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoSuchMethodException: xlSheets.javaFX.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$165(LauncherImpl.java:818)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$179(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$177(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$178(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$152(WinApplication.java:177)
... 1 more
The Application.launch() method uses reflection to create an instance of the Application subclass, calling its constructor taking no arguments.
According to the documentation the Appplication subclass
must be a public subclass of Application with a public no-argument constructor
So in order for this to work, both the Application subclass and the constructor (if explicitly defined) need to be declared public.
The following fixes the problem (I also changed the class name to conform to Java naming conventions):
public class JavaFX extends Application{
#Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("JavaFX app");
Label label = new Label("Hello World, JavaFX !");
Scene scene = new Scene(label, 400, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String args[]) {
Application.launch(args);
}
}

Error with a main method

So I was making a very basic program in java and this happened:
Exception in thread "main" java.lang.ClassNotFoundException: Main
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:259)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:116)
Here is my "program"
public class GUI{
private JTextArea usernameInput;
private JTextArea licenceKeyOutput;
private JButton generateLicenceKeyButton;
private JPanel root;
private JPanel mainGUI;
public static void main(String[] args) {
JFrame frame = new JFrame("GUI");
frame.setContentPane(new GUI().mainGUI);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public GUI() {
generateLicenceKeyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(usernameInput.getText() == ""){
System.err.println("[IntelliGen] Invalid username received, telling user");
usernameInput.setText("Invalid Username");
licenceKeyOutput.setText("Invalid Username");
}else{
}
}
});
}
NOTE: I made this program with IntelliJ Idea's GUI Creator.
It seems that the JDK is corrupted, but it works fine with other programs. Can you guys help me in any way?
In your IntelliJ's launcher configuration Main class is set to Main which is invalid, in this case your Main class is GUI
Run > Edit Configuration > Main class:
Exception in thread "main" java.lang.ClassNotFoundException: Main
This means you are trying to run a class named main, but your class is named GUI

how to run java file in window powershell

I know there are similar questions out there but none of those solutions work for my case.
I tried to execute a Java file using Windows PowerShell.
This is what I have for Java file:
public class Demo1 {
public static void main (String arg[]){
System.out.println("DEMO1 START RUNNING");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Unable to process");
}
System.out.println("DEMO1 JAVA COMPLETED.");
}
}
For easy compilation, I have copies of Demo1.java, Demo1.jar, and Demo1.class in the desktop directory.
for powershell command, I have tried:
1st attempt:
C:..\Desktop> java Demo1.java
2nd attempt:
C:..\Desktop> java -class Demo1.class
3rd attempt:
C:..\Desktop> java -jar Demo1.jar
All the above attempt return this error:
PS C:\Users\b003485\Desktop> java .\Demo1.java
Exception in thread "main" java.lang.NoClassDefFoundError: /\Demo1/java
Caused by: java.lang.ClassNotFoundException: .\Demo1.java
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: .\Demo1.java. Program will exit.

Using Custom Fonts [java.io.IOException: Error reading font data.]

The title doesn't allow me to say Problem, so the actual error message was -
java.io.IOException: Problem reading font data.
at java.awt.Font.createFont(Unknown Source)
at AddFont.createFont(AddFont.java:11)
at MainFrame$1.run(MainFrame.java:105)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
The code is -
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
AddFont addFont = new AddFont();
addFont.createFont();
} catch (Exception e) {
e.printStackTrace();
}
createGUI();
} //public void run() Closing
});
}
and the file that I used to get the AddFont addFont-
import java.awt.Font;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
public class AddFont extends MainFrame{
public void createFont(){
Font ttfBase = null;
Font telegraficoFont = null;{
try {
InputStream myStream = new BufferedInputStream(new FileInputStream(FONT_PATH_TELEGRAFICO));
ttfBase = Font.createFont(Font.TRUETYPE_FONT, myStream);
telegraficoFont = ttfBase.deriveFont(Font.PLAIN, 24);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("Font not loaded.");
}
}
}
}
I was instructed to make a new thread because this is a separate problem from my other one.
Why am I getting this problem, and how can I fix it?
I have my TELEGRAFICO.TTF font in my imageFolder, which is really just my resources folder. I use
public static final String FONT_PATH_TELEGRAFICO = "imageFolder/TELEGRAFICO.TTF";
to call in my path.
What am I doing wrong?
EDIT - I no longer get that error message, and I don't get "Font not loaded". How can I use the font in other class files other than the one I made that method in?
(I want to use that font on buttons in multiple class files. I tried using it here -
regButton = new JButton();
regButton.setText("Foo");
regButton.setAlignmentX(Component.CENTER_ALIGNMENT);
regButton.setFont(telegraficoFont);
But it said telegraficoFont cannot be resolved to a variable. (Because it was in a different class file.)
How can I fix this? Thanks again for the help.
In some cases the cause is the running instance not being able to write to the Java temp directory (java.io.tmpdir).
If your are running it on tomcat maybe you deleted the temp directory of the tomcat installation, or the folder have wrong permissions.
(tomcat folder)/temp
As you have a problem with possible font file locating and font stream creation,
Try this >> Issue loading custom font AND http://forums.devshed.com/showpost.php?p=2268351&postcount=2
To answer your question "how to make this function easy to use everywhere", do as this:
public class AddFont extends MainFrame {
private static Font ttfBase = null;
private static Font telegraficoFont = null;
private static InputStream myStream = null;
private static final String FONT_PATH_TELEGRAFICO = "imageFolder/TELEGRAFICO.TTF";
public Font createFont() {
try {
myStream = new BufferedInputStream(
new FileInputStream(FONT_PATH_TELEGRAFICO));
ttfBase = Font.createFont(Font.TRUETYPE_FONT, myStream);
telegraficoFont = ttfBase.deriveFont(Font.PLAIN, 24);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("Font not loaded.");
}
return telegraficoFont;
}
}
And then in your calling class:
public class Test {
public static Font font = null;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
if (font == null) {
font = AddFont.createFont();
}
} catch (Exception e) {
e.printStackTrace();
}
createGUI();
} // public void run() Closing
});
}
}
In some cases, maybe the Fontconfig is lack in your running environment. After installing, everything is OK.
For example,
yum install fontconfig
you could try to install "dejavu-sans-fonts" and fontconfig, it works

javaPOS adding libraries to project

I've just tried running the sample java files that I got with the epson tm-t20 printer that I bought. These classes should run but they keep giving me errors. I've been looking at this for over 8 hours now I'm really getting frustrated. This is the exception it's throwing at me:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/apache/xerces/parsers/DOMParser
at jpos.config.simple.xml.AbstractXercesRegPopulator.<init>(Unknown Source)
at jpos.config.simple.xml.XercesRegPopulator.<init>(Unknown Source)
at jpos.config.simple.xml.SimpleXmlRegPopulator.<init>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at jpos.loader.simple.SimpleServiceManager.initRegPopulator(Unknown Source)
at jpos.loader.simple.SimpleServiceManager.initEntryRegistry(Unknown Source)
at jpos.loader.simple.SimpleServiceManager.init(Unknown Source)
at jpos.loader.simple.SimpleServiceManager.<init>(Unknown Source)
at jpos.loader.JposServiceLoader.<clinit>(Unknown Source)
at jpos.BaseJposControl.open(Unknown Source)
at postest.Step1Frame.processWindowEvent(Step1Frame.java:83)
at java.awt.Window.processEvent(Window.java:2003)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Here's the sample code I've been looking at:
POSPrinterControl19 ptr = (POSPrinterControl19)new POSPrinter();
JPanel contentPane;
JPanel jPanel_reciept = new JPanel();
TitledBorder titledBorder1;
GridBagLayout gridBagLayout1 = new GridBagLayout();
GridBagLayout gridBagLayout2 = new GridBagLayout();
JButton jButton_Print = new JButton();
/**Construct "Frame"*/
public Step1Frame() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
/**Form the component*/
private void jbInit() throws Exception {
//setIconImage(Toolkit.getDefaultToolkit().createImage(Step1Frame.class.getResource("[Your Icon]")));
contentPane = (JPanel) this.getContentPane();
titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(134, 134, 134)),"Receipt");
contentPane.setLayout(gridBagLayout1);
this.setSize(new Dimension(300, 180));
this.setTitle("Step 1 Print \"Hello JavaPOS\"");
jPanel_reciept.setLayout(gridBagLayout2);
jPanel_reciept.setBorder(titledBorder1);
jButton_Print.setText("Print");
jButton_Print.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton_Print_actionPerformed(e);
}
});
contentPane.add(jPanel_reciept, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(15, 0, 0, 0), 20, 20));
jPanel_reciept.add(jButton_Print, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 10, 5, 10), 130, 0));
}
/**
* Outline The processing code required in order to enable
* or to disable use of service is written here.
* #exception JposException This exception is fired toward the failure of
* the method which JavaPOS defines.
*/
/**When the window was closed*/
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
this.closing();
}
/**When the window open*/
else if (e.getID() == WindowEvent.WINDOW_OPENED) {
// JavaPOS's code for Step1
try {
//Open the device.
//Use the name of the device that connected with your computer.
//ptr.clearPrintArea();
ptr.open("POSPrinter");
//Get the exclusive control right for the opened device.
//Then the device is disable from other application.
ptr.claim(1000);
//Enable the device.
ptr.setDeviceEnabled(true);
}
catch(JposException ex) {
}
}
// JavaPOS's code for Step1--END
}
//***********************Button*************************************************
/**
* Outline The code for using the most standard method "PrintNormal"
* to print is described.
*/
void jButton_Print_actionPerformed(ActionEvent e) {
// JavaPOS's code for Step1
try{
//printNormal(int station, String data)
//A string is sent by using the method "printNormal", and it is printed.
// "\n" is the standard code for starting a new line.
// When the end of the line have no "\n",printing by
// using the method "printNormal" doesn't start, may be.
ptr.printNormal(POSPrinterConst.PTR_S_RECEIPT,"Hello JavaPOS\n");
}
catch(JposException ex){
}
// JavaPOS's code for Step1--END
}
//***********************Method*************************************************
/**
* Outline The code to finish a service.
*/
void closing(){
// JavaPOS's code for Step1
try{
//Cancel the device.
ptr.setDeviceEnabled(false);
//Release the device exclusive control right.
ptr.release();
//Finish using the device.
ptr.close();
}
catch(JposException ex){
}
// JavaPOS's code for Step1--END
System.exit(0);
}
You have to put some additionally dependency library to the project classpath, one of them seems to be the apache xerces XML parser, so basically you have to add that jar library to the classpath .
you can find the apache xerces XML parser here .
For me class org/apache/xerces/parsers/DOMParser is missing. You can download it from maven repository xercesImpl.jar

Categories

Resources