Problem with Java Applet - java

I'm new to Java Applets. I have a problem while reloading the applet. When I resize the applet window or open some other application and then come back to the applet, the contents on the screen is redrawn. Basically my paint method is getting called. I want the contents of the paint method to be called only once. How can I accomplish this? Can anyone please help me with this?
Thanks in advance.

You are misunderstanding how paint works - you have no real control over how many times it is called. What are you doing in the paint method that makes you think you only want to do it once and why is it a problem that it gets called again?
If you're worrying about flickering, then you might like to look at painting into a buffer. Code not directly related to painting should not be in the paint method. You can put other initialization logic in the applet's start method

If you're putting initialization code into the paint method, you might think about putting it into the init or start methods instead.
The phrase you'd be looking for is applet lifecycle.

I am new to java applet design and when running it i get one problem that says "no main"
here is my code:
import java.applet.*;
import java.awt.*;
public class abhidev extends Applet {
/** Initializes the applet abhidev */
public void init() {
try {
setBackground(Color.cyan);
}
catch(Exception e){
e.printStackTrace();
}
}
public void paint(Graphics g){
try{
g.drawString("this ais an applet window",10,30);
showStatus("this is astatus window");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
The applet class name is: abhidev.java.

Related

JFrame keeps application running even after closing

I have a class with only static methods and one of them opens a JOptionPane error message dialogue using a JFrame object as component.
This is the class + method:
public class miscMethods
{
static JFrame errorWindow = null;
public static void ErrorPopup(String message)
{
errorWindow = new JFrame();
errorWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
errorWindow.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(errorWindow, message, "Error", JOptionPane.ERROR_MESSAGE);
errorWindow = null;
}
}
The ErrorPopup method is used inside a JavaFX controller and other places, called like this:
import static code.miscMethods.ErrorPopup;
...
ErrorPopup("This is the error message");
Problem is that the application's process won't close when I close the the program from the window's ✕ after the popup appears, because the JFrame was created and shown.
I know the JFrame is the culprit, so I added the errorWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
but it doesn't seem to do anything, since the program isn't closing.
In this question: JFrame and why stay running
The accepted answer talks about non-daemon threads, but the only thread I open is a daemon one, so unless JavaFX open one then it can't be that I believe.
So, why does the process keep running and how can I solve it?
I'm still new to Java so if I made a mistake and/or my code shows bad practices please do point them out!
Edit: I'm using a JFrame because I need the setAlwaysOnTop, since using
JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE); opens it not on top of the JavaFX window. If there's a better way let me know.
This:
errorWindow = null;
does nothing of use since the object is still displayed. You want this instead:
errorWindow.dispose();
Actually, even better, simply get rid of errorWindow altogether and pass null as the first parameter to the JOptionPane.

How to restart a java program within the program

I'm working on a small Java game using Swing for school, and we need to implement a button that "starts a new game" when pressed. The problem is, the game takes multiple parameters from String[] args, so I can't just call the "main" function (where everything is instansiated) again from another class. Any way to do this?
You certainly can call main() from inside your application. But it's also certainly not what you want to do. Instead try moving the instantiation code into another function, most likely a constructor of some type of Game object. Then you can instantiate a new game from both main as well as some kind of restart function without any unintended consequences of calling main from inside your application.
You can use the following code to run a program. Unless your button and game are in the same package, be sure to import it (which will look like import packageName.className).
JButton newbutton = new JButton("New");
newbutton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new className(); //run the class you want to here
}
});
}
});
If you have any questions about this code, please comment below.
You have to lauch your program before exit it.
Runtime rs = Runtime. getRuntime(); try { rs. exec("java -jar your_restartable_program.jar"); }

Call to jFrame from jInternalFrame does not work

I have a main jFrame HomePage.java and many other classes which extend javax.swing.JInternalFrame. One of the classes (JInternalFrame) is Login.java. Now I check whether the password is correct in Login.java and if the password is correct, I load success.java. Now the problem arises when I have to load the success.java page.
I have a function in the HomePage.java whose purpose is to remove all internal frames and load success.java class. The function is as follows :-
public void LogIn(){
jDesktopPane1.removeAll();
System.out.println("Pos 2");
success frame = new success();
frame.setVisible(true);
jDesktopPane1.add(frame);
setContentPane(jDesktopPane1);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
I call the function in the Login.java page as follows :-
System.out.println("Pos 1 ");
(new HomePage()).LogIn();
The logic does not work. But, I receive the output as
Pos 1
Pos 2
which shows that the program flow was correct. I do not get any error also. Another weird factor is that when I calthe same LogIn() function from the menu in the jFrame itself, I get the desired output. Please solve my dilemma. Any help will surely be appreciated!
This code:
System.out.println("Pos 1 ");
(new HomePage()).LogIn();
Creates a new HomePage object and calls a method on it. Oh you are certainly calling the correct method, and it's going a HomePage instance, but it's not the correct HomePage instance, not the one that's displayed, because you've created a new one.
Short term solution: get a valid reference to the displayed HomePage instance and call your method on it. You could get it by passing it into the class that needs it as a constructor or method parameter, or you could use SwingUtilities.getWindowAncestor(...).
i.e.,
Window window = SwingUtilities.getWindowAncestor(Login.this);
if (window instanceof HomePage) {
HomePage validHomePageRef = (HomePage) window;
validHomePageRef.logIn();
}
Long term solution: don't create spaghetti code with GUI objects changing behaviors of other GUI objects, but instead refactor your code a la MVC or one of its variants, so the GUI can change the model and the other GUI objects can be notified of these changes via listeners and respond if they want.

UIManager.getColor returns null sometimes

I have an applet that is generating a nullpointer exception at this line (but only sometimes) at load time:
(txtpnNoSeHa is a JEditorPane inside a class that extends JPanel. This panel is instantiated inside the applet constructor)
txtpnNoSeHa.setBackground(UIManager.getColor("Panel.background"));
called inside the constructor.
What I understand from this is that UIManager.getColor returns null sometimes maybe because some data has not been loaded (no swing panel has been shown or something similar)
The applet was designed with eclipse's window builder. How can I fix this? Any one can shed some light into this?
As you had predicted, the UIManager is loaded as soon the first swing component is made visible. This may lead to null values. You can manually load the UIManager with this call at the beginning of the main routine (or init for applets):
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch(InvocationTargetException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
I had similar issue in the past, and I solved it by making every swing-related code to be run from the GUI-thread (EDT).
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
// ...
}
});

LWJGL Game not properly ending

I currently have a simple problem with LWJGL right now. If I were to run my game, it does actually run everything correctly and it appears to close out correctly, but when I look inside my Task Manager, I notice that my game is taking up 25% CPU after I close it (about 2-3% when it's actually running) and I'm thinking that I may have missed something when ending the application.
My main function code:
public static void main(String[] args){
try {
init();
}catch(LWJGLException e){
System.out.println("LWJGLException\n");
e.printStackTrace();
}
try{
gameLoop();
}catch(Exception ex){
ex.printStackTrace();
}finally{
cleanup();
}
}
cleanup:
public static void cleanup(){
System.out.println("Running cleanup code.");
Display.destroy();
System.exit(0);
}
It does actually manage to read "Running cleanup code." My problem is that I don't know if there is something else I need to do to clear out all of the processes. This game is also using a single thread.
There is nothing wrong with your code at all, I think. If your problem is what I think it is you wouldn't be able to immediately fix it.
Here are some basic questions you should ask your self. What OS are you using? What is your Java version and/or LWJGL version? (Updating them might help) Have you ever heard of/or played a game called Minecraft? If you are using Linux and seen this when closing Minecraft then that could be the problem you're having.
I have had the same problem on 64-bit windows. App haven't closed when Runtime Exception (or any other uncaught exception) occured. Probably reason was throwing an exception in an independent thread which effected in closing display window, but all other threads were still working. I came up with brute force solution: overriding Thread method.
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void uncaughtException (Thread thread, final Throwable ex) {
ex.printStackTrace();
Display.destroy();
System.exit(0);
}});
new LwjglApplication(new StartScreen(application), cfg);

Categories

Resources