I am writing a small java app to control the order process for a friend.
I am using the PrinterDialog construct to call the system printers and it seems to work pretty well on my Mac under development. However when I try the same code on a Windows machine the code will not open the system printer dialogue. There is no obvious "code failure", just nothing happens. I have tried copying the Jar file to windows and also re-compiling the project on NetBeans within Windows and neither seems to make any difference. There was a thread similar to this a year or two back but the writer seemed to imply simply re-building the project on a Windows machine had solved the problem when, for me, it seems to make no difference.
Any comments or pointers to get the app to work on Windows would be gratefully received.
The code in question is:-
private void actionPrint(ActionEvent event) {
try {
Stage printStage = new Stage();
FXMLLoader ploader = new FXMLLoader(getClass().getResource("OrderDocument.fxml"));
Node orderNode = (Node) ploader.load();
Group printerNode = new Group();
printerNode.getChildren().add(orderNode);
Scene printScene = new Scene(printerNode, 620, 875);
printStage.setScene(printScene);
Printer printer = Printer.getDefaultPrinter();
PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
PrinterJob job = PrinterJob.createPrinterJob();
job.showPrintDialog(printStage);
if (job != null) {
boolean success = job.printPage(pageLayout,printerNode);
if (success) {
job.endJob();
}
}
} catch (IOException ex) {
Logger.getLogger(OrderCreateController.class.getName()).log(Level.SEVERE, null, ex);
}
}
The line calling "showPrintDialog" has as its owner the stage on which I built the order document.
However re-reading the usage of "showPrintDialog" I now think it should refer to my main stage and when I effected this change the code worked on both Windows and Mac.
I am a little puzzled as to why the above code did work on Mac in the first place and this rather blinded me to finding it as a solution on Windows, so if anyone has any thoughts on that I will leave this open for a few days.
Related
I have a Java program that is built, and is running as a standalone .Jar file. The last build was in start November, and it, along with the previous builds, have been running smoothly.
The function that has stopped working, is where the user wishes to print a receipt, and the program used to show a "Select printer" dialog screen.
But as of today, when the button that runs this function is clicked, nothing happens. The button click effects runs as they should, so the click is registered, but nothing else happens.
I have tried running the .jar file on both my own, and the users computer with same negative result.
However, when i run the project in IntelliJ, and click the button, everything works as it should, with no exceptions or warinings anywhere. I then tried rebuilding it using this very same code. But again, as a separate .jar file, nothing happens. The user, used the very same function as intended just 2 days ago, with the same .jar file that is not working now.
Edit: Opening the jar file in the commandwindow gives a NullPointerException at the line mentioned below.
A remote debug gives this explanation of the object beleived to cause the exception:
JavaFX PrinterJob Printer Microsoft Print to PDF
Collation = UNCOLLATED
Copies = 1
Sides = ONE_SIDED
JobName = JavaFX Print Job
Page ranges = null
Print color = COLOR
Print quality = NORMAL
Print resolution = Feed res=600dpi. Cross Feed res=600dpi.
Paper source = Paper source : Automatic
Page layout = Paper=Paper: A4 size=210.0x297.0 MM Orient=PORTRAIT leftMargin=54.0 rightMargin=54.0 topMargin=54.0 bottomMargin=54.0
Job Status = NOT_STARTED
public class PrintPage {
public void printSetup(Node node, PageOrientation or)
//The class where it prompts for the printer to be used.
{
Stage stage = new Stage();
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null) {
//Line below gives NullPointerException at the job.showPrintDialog(stage) item
if (job.showPrintDialog(stage)) print(job, node, or);
}
stage.close();
}
The errorstack leads from the line above to this part in the javafx PrinterJob class.
public synchronized boolean showPrintDialog(Window owner) {
// TBD handle owner
if (!isJobNew()) {
return false;
} else {
//This line is the next in the stack
return jobImpl.showPrintDialog(owner);
}
}
which leads to an error in:
com.sun.prism.j2d.print.J2DPrinterJob.showPrintDialog(J2DPrinterJob.java:161)
The only null item i see is the Page Ranges, which i can't seem to set.
I noticed that recently when I run my LibGDX game it takes a good 20 seconds to boot up which is strange because I'm only loading a few resources. I put breakpoints in my main method to pinpoint where the app was getting stuck, and it turns out it's getting stuck when I call this line:
new Lwjgl3Application(new GdxGame(), config);
In the Lwjgl3Application constructor, it is hanging on this method call:
initializeGlfw();
Which looks like this:
static void initializeGlfw() {
if (errorCallback == null) {
Lwjgl3NativesLoader.load();
errorCallback = GLFWErrorCallback.createPrint(System.err);
GLFW.glfwSetErrorCallback(errorCallback);
if (!GLFW.glfwInit()) {
throw new GdxRuntimeException("Unable to initialize GLFW");
}
}
}
In this method it gets stuck on createPrint and GLFW.glfwInit(). The print method looks like this:
public static GLFWErrorCallback createPrint(PrintStream stream) {
return new GLFWErrorCallback() {
private Map<Integer, String> ERROR_CODES = APIUtil.apiClassTokens((field, value) -> 0x10000 < value && value < 0x20000, null, GLFW.class);
#Override
public void invoke(int error, long description) {
String msg = getDescription(description);
stream.printf("[LWJGL] %s error\n", ERROR_CODES.get(error));
stream.println("\tDescription : " + msg);
stream.println("\tStacktrace :");
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
for ( int i = 4; i < stack.length; i++ ) {
stream.print("\t\t");
stream.println(stack[i].toString());
}
}
};
}
All of these methods come from the Lwjgl library. Does anybody know why my app might be getting stuck on these method calls?
I've had the same issue and it seams to be tied to the machine you are on. I made a clean VS15 solution with GLFW and ran it on several different PCs to find that only my desktop had this issue. I also tested the LWJGL binding of GLFW and had the same results.
[EDIT] the wait happens in the glfwInit() call
/* Initialize the library */
if (!glfwInit()) // stuck here
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(1920, 1080, "Hello World", NULL, NULL);
There is one post that I came across an archived post on the openGL forums that mentions an issue similar to this but it's fairly old and might be referring to a slightly different issue.
I can recommend to check that you are excluding your build folder from any antivirus, sometimes they see the generated executables as potential threats and thus might be slow however i dont believe that's your issue.
Sadly the only option that has worked for me was a clean install of windows, though the bug mysteriously stopped manifesting itself when I connected a VR headset and reappeared a couple days later. Hope you have better luck than me and dont have to clean install your OS and if you find a less cumbersome solution be sure to spread the word.
I'm working on an Eclipse RCP project and need to let the user select some file.
For convenience, based on some conditions, the initial directory of the file choosing dialog should be set prior to opening it.
As I'm bound to Eclipse RCP / SWT, I am working with the org.eclipse.swt.widgets.FileDialog.
The documentation of this FileDialog points out to use the setFilterPath(String string)-method which should do exactly what I need (see documentation).
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.html"});
dialog.setFilterPath("c:\\temp");
String result = dialog.open();
Unfortunately it is not working, at least not "every time".
I have currently no installation to check on it, but I'm quite sure that the feature would work totally fine on a Windows 200/XP/Vista machine.
I am working with a Windows 7 machine and I think I am suffering from the behaviour described here for lpstrInitialDir.
At least, this is exactly the behaviour I am facing: The path is good the first time I open the dialog, but the second time, the path is initially set to the last chosen path.
This seems to be convenient in most cases, but it is not in mine.
Can this be right?
If so, have I any chance on changing the behaviour according to my needs?
Thanks for any helping answer!
I ran into the same problem on Windows 10 and found a solution that seems to be working for me. A code snippet from the DirectoryDialog led to the right direction:
if (filterPath != null && filterPath.length() > 0) {
String path = filterPath.replace('/', '\\');
char[] buffer = new char[path.length() + 1];
path.getChars(0, path.length(), buffer, 0);
if (COM.SHCreateItemFromParsingName(buffer, 0, COM.IID_IShellItem, ppv) == OS.S_OK) {
IShellItem psi = new IShellItem(ppv[0]);
/*
* SetDefaultDirectory does not work if the dialog has
* persisted recently used folder. The fix is to clear the
* persisted data.
*/
fileDialog.ClearClientData();
fileDialog.SetDefaultFolder(psi);
psi.Release();
}
}
The FileDialog misses this statement 'fileDialog.ClearClientData()'. My solution is to execute the following code before setting the path and open the dialog:
long [] ppv = new long [1];
if (COM.CoCreateInstance(COM.CLSID_FileOpenDialog, 0, COM.CLSCTX_INPROC_SERVER, COM.IID_IFileOpenDialog, ppv) == OS.S_OK) {
IFileDialog fileDialog = new IFileDialog(ppv[0]);
fileDialog.ClearClientData();
fileDialog.Release();
}
Now you can set the filterpath without Windows messing things up.
I found a simple Solution for the Problem you described (I had the exact same Problem).
Just rearrange the your code like this:
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterPath("c:\\temp"); // This line is switched with the following line
dialog.setFilterExtensions(new String [] {"*.html"});
String result = dialog.open();
Somehow the Order of the methods called is relevant.
Are you using the same FileDialog object when you re-open it?
I ran a few quick tests and found that, if you re-set the filterPath, the dialog opens in the correct location.
If I open the same object again, it starts in the previously selected location.
I'm writing an application that runs in the System Tray and notifies the user (i.e. makes one of those bubbles pop up) when something happens. The only problem is that the notifications only seem to work on Windows 7, and not Windows XP.
I've tested it on 2 Windows 7 computers (they've both worked) and 4 Windows XP computers (none of them have worked). No notification bubble is shown, and (as far as I know) no exceptions are thrown and everything else works as it should. I've even tested it on a Mac, and it worked, but it wasn't too pretty.
Here is a sample of my code.
private static TrayIcon trayIcon;
...
trayIcon = new TrayIcon(trayImage.getImage());
...
if (!SystemTray.isSupported())
{
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();
final SystemTray tray = SystemTray.getSystemTray();
trayIcon.setToolTip("Widget Name Here [" + role + "]");
...
try
{
tray.add(trayIcon);
}
catch (AWTException e)
{
System.err.println("TrayIcon could not be added.");
return;
}
...
//Here's where it doesn't work on XP
trayIcon.displayMessage("Connection error",
"Could not connect to server, please check your internet/VPN "
+ "connection", TrayIcon.MessageType.ERROR);
Any help would be much appreciated.
UPDATE: Ok, I've just confirmed that it's not a problem with my program, but a problem with the XP installations I've been testing them on. I ran the TrayIconDemo.java program found here on an XP computer and none of the notifications worked. I'm starting to think there's nothing I can do to get it to work on one of these computers...
Okay, so I've finally found the solution to my problem. It turned out that the following key was set to 0 (false) by default on the installations I was testing on:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\EnableBalloonTips
To enable the notification bubbles, simply set the value to 1.
I have Windows XP and working on system tray application. I have just added displayMessage() and it works just fine for me. Try to simplify your application. I am sure it will work. The find a bug.
EDIT: you didn't mentioned JRE version System try required Java6
this should be comment, but this is restrict for chars lenght
maybe, there is another reason in case of when Java updates are distributed by some of administrations tool for AD or ZenWorks, then sometimes (on both win7/Xp) is needed un-install all java instalactions and install fresh JRE manually (but stable 1.6.022 my view), sw distibutions ends without error, but all (???) classes/methods/changes cames from Java6 weren't accesible, on partial (RowSorter etc...) test ends with error, and I never search for knows Bugs on MS, Novell ...
I'm printing a complicated swing application UI to a physical printer via an Airport. I've got Mac & windows machines both printing to the same printer. Printing from the Mac looks great. Printing from windows looks far from great - everything is very pixelated, including fonts and graph lines.
Some digging around reveals that the available PrintServices are different for the different platforms.
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();
PrintServiceLookup.lookupPrintServices(flavor, attrs);
When executed from the mac, the above returns a single-element array. From windows, it returns an empty array. This leads me to believe that windows is sending a 72 DPI image to the printer, instead of postscript data.
Is this a difference in the mac & windows JVM implementations? Is there any workaround to get printing on Windows working? I realize I could generate my own 350dpi rasterized image and send that to the printer, but these things go into the hundreds of pages, I really would like to avoid that route if possible.
Think I got an answer: The java.awt.printerjob system property was set to sun.awt.windows.WPrinterJob. Apparently this is a handy PrinterJob subclass if you like blocky pixelated output on your printer. Instead, I get an instance of sun.print.PSPrinterJob if it's available, like so:
PrinterJob printerJob = null;
try {
if (System.getProperty("java.awt.printerjob").equals("sun.awt.windows.WPrinterJob")) {
// WPrinterJob sends crappy GIF images to the printer, and everything looks all blocky
// try to get an instance of a PSPrinterJob instead
printerJob = (PrinterJob) Class.forName("sun.print.PSPrinterJob").newInstance();
}
} catch (Throwable e1) {
log.log(Level.SEVERE, "Could not instaniate sun.print.PSPrinterJob", e1);
}
if (printerJob == null) {
printerJob = PrinterJob.getPrinterJob();
}