How to ensure execution of latest version of class file? - java

OK so I started with this:
import java.awt.*;
import java.applet.*;
public class Oval extends Applet {
public void paint (Graphics g)
{
g.setColor(Color.red);
g.fillOval(50,50,70,70);
}
}
Saved it as Oval.java. Then I ran javac Oval and it spits out the class file. Linked the class file to my HTML and all was good. Then I tried to change the color of the oval to say Color.blue and everything was not so good. I just changed the code in the Oval.java file, then re-ran the javac Oval and the result was a "new" class file... but it's the output is the exact same.
Do I have to "reset" the memory space or something? I have tried for some time to get the answer but I simply lack the vocabulary to accurately ask the question.

Sounds like the browser is caching the class file. I would try
Running the applet using the Applet Viewer
If that works, then it's a browser caching issue (clear your browser's cache)
But if it doesn't look different, or like you want in the Applet Viewer, then it must be something in your local environment (either it's not building the source file you want, or the class is going somewhere unexpected)

It could be that your browser is caching the previous version of your applet. Try clearing / disabling your cache.

Maybe the old version is in your browser-cache? Try hitting the follwing keys on your page:
Windows: ctrl + F5
Mac/Apple: Apple + R or command + R
Linux: F5

You don't have to reset the java environment, ever.
You might have a browser window open, and your browser is attempting to be "smart" avoiding reload of a page which is already "fetched". Depending on the browser, you will need to learn how to clear the browser cache.

Related

Converting JFrame code to JApplet [duplicate]

I have a JFrame application working nicely. However now I'd like to run it on the web as an Applet. This is what I've done:
import MyPackage.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class MyName extends JApplet
{
public void init() {
setSize(600,450);
new MyName()
}
public MyName() {
JShellFrame frame = new JShellFrame(true, null, null);
frame.setVisible(true);
}
}
How can I make an html file to run this applet? Also, I have an external jar file that the applet will need. Does the applet not need a main method?
Check out Getting Started With Applets. It covers relevant methods and life cycle. It mentions main method as well:
Unlike Java applications, applets do not need to implement a main
method.
Deployment section covers HTML file details. For dependency jars you can specify more than one jar in archive attribute of applet tag.
However now I'd like to run it on the web..
Then drop this nonsense and launch the frame from a link using Java Web Start. I say 'nonsense' for two reasons.
JWS has existed since Java 1.2, & has been discussed in these forums several times in the last few days in regard to applets. Seems you are not doing much research.
Of the 'gargantuan' 2 lines of applet code code shown above, one of them is ill-advised and the other is either pointless or would risk creating a stack overflow error (could not be bothered trying it to find out which).
here's some html that will work:
<applet archive = "appName.jar" width = 900 height = 506 code = "main.class"/>
You can change the width and height according to the size your app needs. Also make sure to put the url as a path to the jar.

I have unsuccessfully tried to use images with JApplet for TWO days. What have they done to Java? Where am I going wrong?

EDIT: To those idiots who negged this question merely over the title, the button is clearly meant to be pressed if the question is out of the blue, without any effort put into it at all. I have researched and I have asked, and I have tried. All I am asking for is help.
It's hardly necessary to say just how much work I have put into trying to find a solution to my problem - I have asked questions, Googled, read documents, you name it, but all to no avail.
What I want to do is something I thought I could figure out within minutes: How to run images with JApplet, and use these images in the paint(Graphics g) function. I am running the JavaProject.html file from the build (also known as bin) folder, and it is from the file system, not HTTP. I did not include the "package" line in my code as well.
A recap of my journey is that the following have not worked for me:
This is my HTML file:
<html>
<head>
<title> My First Web Page </title>
</head>
<body>
<applet code="JavaProject.class" width="500" height="600">
</applet>
</body>
</html>
This method gives me the "Access Denied" "java.io.FilePermission" "Image.jpg" "read" Error. Needless to say, trying to work with images on a website does not work either. This one is one of the more frustrating ones because it works to with other people, yet not for me.
import java.applet.*;
import java.awt.*;
public class JavaProject extends JApplet
{
Image image;
public void init()
{
image=getImage(getDocumentBase(),"/Space.gif");
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(image,20,20,this);
}
}
So that one didn't work. They suggested the getResourceAsStream method, so I tried that.
Image image;
Exception lastException=null;
try
{
image=ImageIO.read(getClass().getResourceAsStream("/Space.gif"));
}
catch (IOException ex)
{
lastException=ex;
}
But this one ended up giving me the "Illegal Argument Exception" input=null! Error.
This is my file arrangement: http://oi61.tinypic.com/5ohydc.jpg
Most other methods do not really work or are just far too complex to write down here, but none seem to work. I ask then, is my last resort just to get this thing signed? I have no idea how to go about doing that, and I think it's ridiculous that I even have to go through the trouble just to display images on my JApplet.
I have really lost all faith, and if this is to be fixed no doubt it will take enormous patience, but I would really appreciate any help. I am new to Java, so I can't really discuss much technically, but I pick up from examples rather quickly.
The first method you attempted does work. The only change you need to make is to remove the slash ( / ) before the file name you are attempting to use. Here's your original code (which works fine) with that one character removed:
import java.applet.*;
import java.awt.*;
public class JavaProject extends JApplet
{
Image image;
public void init()
{
image = getImage(getDocumentBase(),"Space.gif");
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(image,20,20,this);
}
}
Note that in order for this to work, your 'space.gif' image must be in the root directory of your project, alongside the Java file that references it, like in this picture:
See how the image is in the 'default package' directory where my JavaProject.java file is also located? Use the code above, make sure your image is in the right place, and your program will run successfully. Here's mine in a running state:
The reason that the second attempt is failing is that it can't find the resource at the path you gave. That causes getResourceAsStream to return null which then results in the exception message that you saw.
You say that the error message in the first case was "Access Denied" "java.io.FilePermission" "Image.jpg" "read" or something. But according to the code, you are not trying to load "Image.jpg". That might be the root of your original problem.
A related issue is that in the getResourceAsStream version, you are using the wrong absolute path. You've used the path "/Space.gif", but given where you have put the file, it should be "/javaproject/Space.gif". Alternatively, since you are calling getResourceAsStream as on a class in the same (javaproject) package that contains the file, you could also use a relative path; i.e. "Space.gif".
I have really lost all faith, and if this is to be fixed no doubt it will take enormous patience ...
Actually, the real solution is to carefully read the documentation for the classes / methods you are using, rather than replying on random examples you found on the internet.

Java Clipboard on Linux (text only), some programs can read it, others can't, why

When my Java-based application (not a browser-based applet) copies plain text to the system clipboard on Linux, many programs are not able to access the clipboard data, but some are.
Here's the simplest test I could make:
import java.awt.datatransfer.*;
import java.awt.Toolkit;
import java.io.*;
public final class PasteTest {
public static void main (String... args) {
String mytext = "This is a test message, testing, 1, 2, 3....";
StringSelection sel = new StringSelection(mytext);
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
clip.setContents(sel, null);
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
While this program is running, File > Paste in OpenOffice (LibreOffice 3.5.7.2) is able to access the text it placed on the system clipboard. But using File > Paste in Gnome Terminal, Mozilla Thunderbird & Firefox, and many other programs can not. The Paste option is gray, as if the clipboard is empty.
How can I make my Java program publish plain text to the system clipboard on Linux (testing on Ubuntu 12.04) so all programs can access it?
Your code is fine. Its problem is that it terminates too soon.
Under X window system, the process that puts something on 'clipboard' (that is, the selection named 'clipboard') must stay alive for the copied data to survive. (Read about active and passive buffers, and notice that selections are of the active kind).
While your process runs, that is, sleep()s, you can paste the data anywhere. Once it terminates, clipboard goes empty.
This is not special behavior of Java; you can easily reproduce it with charmap or any other program you don't mind closing.
I don't know how LibreOffice scored a point in your test. Possibly it was first on your alt+tab list. In my tests, LibreOffice behaved like any other app: 'paste' worked as long as the Java process was alive, and stopped working as the process terminated.
I don't know how to fix it in general case. Running a clipboard manager (that remembers multiple copied items and thus probably owns all of them) might help.

Is there a way to expand a JFileChooser directory without a mouse

Using a JFileChooser, I can select a directory by double clicking the directory (going down a level) with my mouse. Is there a way to select a directory without the mouse? For example, is there a key binding to go down a directory level or do I have to somehow add a key listener to the JFileChooser?
You should be able to use tab to move between the different parts of the chooser, and then use the arrow keys to change which directory is highlighted, and then press Enter to change the directory to the highlighted one.
I have tested the following example code on my machine (Vista/JDK 1.6) and it works as I would expect:
import javax.swing.*;
public class test {
public static void main(String[] args) {
(new JFileChooser("")).showOpenDialog(new JFrame());
System.out.println("OK!");
}
}
If your project is not responding similiarly in your JFileChooser, I would debug as follows:
Create test.java with only the code necessary to pop up a chooser.
If the test app differently than within your app, its something in your code causing it to fail, such as UI skinning code, keyboard listeners, etc. Modify the example, one change at a time to closer replicate your settings for your chooser in your app and see if you can pinpoint where it breaks.
If even a basic test app doesn't work right, it is probably something about your setup, such as a bug in your JDK version, your OS, etc. Troubleshoot your setup.
Have you tried the space-bar or enter key?
Try using ctrl+enter key to select directory.
This behavior is happened when you set to JFileChooser file selection mode to “files and direcories”:
JFileChooser fileBrowser = new JFileChooser();
fileBrowser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

How to give focus to default program of shell-opened file, from Java?

From within Java, I am opening an Excel file with the default file handler (MS Excel, in this case :-) ) using the method described in this stackoverflow question:
Desktop dt = Desktop.getDesktop();
dt.open(new File(filename));
However, the Excel program doesn't get the focus. Is there any easy way to do so?
Edit: There is a related stackoverflow question for C#, but I didn't find any similar Java method.
Edit 2: I've did some simple tests, and discovered that Excel starts and gets the focus whenever no instance of Excel is running. When Excel is already open en NOT minimized, the application doesn't get the focus. If instead the Excel Windows was minimized, the above code will trigger a maximization of the window and Excel getting the focus (or vice versa :-) ).
If you only care about Windows (implied in the question), you can change the way you invoke Excel: use "cmd start...".
I have been using this piece of code to launch Windows applications for some time now. Works every time. It relies on the file association in Windows to find the application. The launched application becomes the focused window on the desktop.
In your case, Excel should be associated with .xls, .csv and other typical extensions. If it is, Windows will launch Excel, passing your file to it.
Usage:
MyUtilClass.startApplication( "c:\\mydir\\myfile.csv", "my window title" );
file is the full path to the input file for Excel and title is the window title (the application may or may not take it - Excel changes the window title).
public static void startApplication( String file, String title )
{
try
{
Runtime.getRuntime().exec( new String[] { "cmd", "/c", "start", title, file } );
}
catch( Exception e )
{
System.out.println( e.getMessage() );
}
}
From a scala-program, which runs in the JVM too, I can open an application, and that get's the focus by default. (Tested with xUbuntu, which is a kind of Linux).
import java.awt.Desktop
val dt = Desktop.getDesktop ();
dt.open (new java.io.File ("euler166.svg"));
I can't say, whether this is specific for Linux, or maybe something else - however starting Inkscape in my example, excel in yours, may take a few seconds, while the user impatiently clicks in the javaprogram again, thereby claiming the cursor back. Did you check for that?
You could then change to the last application, at least on Linux and Windows with ALT-Tab aka Meta-Tab (again shown in scala code, which you can easily transform to javacode, I'm sure):
import java.awt.Robot
import java.awt.event._
val rob = new Robot ()
rob.keyPress (KeyEvent.VK_META)
rob.keyPress (KeyEvent.VK_TAB)
rob.keyRelease (KeyEvent.VK_TAB)
rob.keyRelease (KeyEvent.VK_META)
but unfortunately the unknown source off more trouble, also known as user, might do nothing, so switching would be the false thing to do. Maybe with a thread, which checks for a certain amount of time, whether the java-program has the focus, but it keeps a form of roulette, in an interactional environment, because the user may have a fast or slow machine, or change to a third application meanwhile, and so on. Maybe a hint before triggering the new app is the best you can do?

Categories

Resources