How to execute some action after the JFrame are displayed - java

I have this GUI application, and I want to execute a custom action inmediatelly when the user open the application, but after the GUI are shown.
So, I put the call to the action into the public Main() of the JFrame like this:
public Main() {
initComponents();
ExecuteAfter();
}
Where ExecuteAfter() is the method that contain the acction, or actions to execute.
This works fine, but not in the way I want. This way, the action executes allways before the JFrame are displayed, that is before the aplication windows appear in the screen. What I want is that execute the action only after the JFrame are displayed, that is after the aplication windows appear in the screen.
I tried put the call into the public static void main(String args[]) because there's where the JFrame is created and displayed. But doesn't work because the method isn't static, and I can't put static that method because it use some components of the JFrame that are already initialized non-static by the IDE.
So, the question is: Where I need to put the call for the action can be executed after the JFrame are displayed on the screen? Or there's other way of doing that?
Thanks in advance!

I used a WindowListener and solved the problem.
Instead of put the call in the constructor public Main() or in the main public static void main(String args[]) which cannot be done, I configured a WindowsListener for do the call. Like that:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
ExecuteAfter();
}
And works perfectly in the way I want.
Thanks #MadProgrammer for the tip.

If i understand you question, I use a similar case for my project. I was needed to start timer when JFrame show, so this is how i do that.
So i use 2 methods and 1 constructor. First method (exp. Name: prepare GUI), here you can add all thinks what you need to create JFrame, JPanel....and that method I call in constructor. In second method (exp. Name: start GUI) you will add all components to JPanel/s, JPanel/s to JFrame, and set JFrame visible = (true) and then add your method ExecuteAfter(). That second method(prepare GUI) you need to call in main method. I hope that's will help you.

Related

Netbeans Java Interface won't display when called in the main class

I have designed a Java Interface in Netbeans, however when I try to run it in the main class, instead of displaying, a blank new window is created in the corner of the screen.
This is my code:
private static User_Interface myUI = new User_Interface();
public static void main(String[] args) throws InterruptedException, IOException{
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
myUI.setVisible(true);
}
});
}
I have already tried to implement advice from this question
NetBeans Java Project Won't Display GUI Window Despite No Error
however this still doesn't help.
The interface code is all just the generated code from designing the interface, with a few setText() methods and empty actionPerformed methods. It does extend JFrame though.
Any help would be fantastic, thanks.
I guess.. There may be an issue with your layout manager. Set the layout to null or any other with which you are comfortable. In netbeans you have to select a layout according to your need. In my case the default layout was gridBagLayout that was alot pain for me while resolving the issue. Simply check your layout first. May be that resolves your issue.
Sorry for wasting your time, it appears that the source code for the interface was missing it's initComponents() method.

NetBeans Swing TextArea is not static, causes trouble

I have created a JFrame with a textArea called 'outputTextArea' and I want to print the results from a database query in the textArea. However, the variable outputTextarea is not static and therefore I can't call the method setText() in the main method to print the db resultset in the textArea.
I would like to know how I can make this variable (private javax.swing.JTextArea outputTextArea;) static, because NetBeans won't let me edit this variable because it was generated by NetBeans when I dragged and dropped the textArea.
I had the same problem.
In Netbeans IDE 8.0.2:
1) In the design tab
2) Click on the textarea
3) go to properties -> code
4) Variable Modifiers -> add static.
It worked for me.
Just add an accessor method to your class that adjusts the field. For instance:
public void setTextAreaText(String newText) {
outputTextArea.setText(newText);
}
Then anyone with a reference to your class can adjust the text in the text area. Just be sure to call that method from the Event Dispatch Thread. This is usually achieved with SwingUtilities.invokeLater
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myClassReference.setTextAreaText("Hello, World");
}
});
See the documentation on Event Dispatch Thread if this sort of thing is new to you. It's important to get threading correct when using Swing.
If you just want to edit codes. Open code with another editor just like notepad or something. And if you remove GEN-BEGIN:initComponents just before the auto generated code you can edit code through netbeans also.

Lag before JFrame event handlers are added?

I'm working on a simple Java swing project. This is the code of the main class (name changed):
public class MainProg
{
private static MainProg program;
//mainWin is a JFrame
private MainWindow mainWin;
//Event handler class which extends MouseAdapter
private TrayManager trayMgr;
public static void main(String[] args)
{
program = new MainProg();
}
public MainProg()
{
mainWin = new MainWindow();
trayMgr = new TrayManager();
mainWin.startBtn.addMouseListener(trayMgr);
mainWin.setVisible(true);
}
}
As is clear, when the program starts, in main() it creates a new instance of the MainProg class, which then calls the constructor. In the constructor, it creates a new instance of the JFrame mainWin. It then attaches an event handler to a button on mainWin.
In the event handler class trayMgr, the only method is mouseClicked() which does nothing
except a System.out.println('Clicked');
The issue is, when I run this program in Netbeans, the JFrame is shown right away, but I seem to have to click the button 2-3 times before the message is printed in the console.
Is this just something specific to Netbeans, or do I have to change something to make the event handler be set before the window is made visible?
Your threading issue is not likely one that is causing your current problem, but there's the theoretic potential for problems, and I've seen some real problems associated with some of the more touchy look and feels. Quite simply you should queue your code that starts your GUI onto the Swing event thread. You do this by doing:
public void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(
public void run() {
program = new MainProg();
}
));
}
Someone else recommended using invokeAndWait(...) instead of invokeLater(...) but this can be risky especially if you inadvertently make this call from within the Swing event thread itself. For your situation you're better off using invokeLater(...).
But again, I think the main problem with the code you have shown was inappropriate use of MouseListener where an ActionListener should have been used. Learning to code any GUI library can be quite tricky, and for that reason, you can't assume anything. Check out the tutorials and learn from the experts. Also if you are considering coding Swing for the long haul, consider ditching the NetBean's code-generation utilities and learn first to code Swing by hand. You won't regret doing this.
Since you asked, the code I posted here is a Java SSCCE on a different topic. invokeLater is a way of running computations on the EDT. (There is also invokeAndWait, which would work fine here, but under some other conditions can cause a deadlock.)
In fact this example is perhaps a bit over-conservative. Some references say you can run Swing from the main thread the call to show() or setVisible(). However I have a program that misbehaves under Java 7 when I try that.

Creating a GUI with ActionListeners inside a method

I have a method inside one of my classes to my Java application that makes a Swing GUI and has it's own action listeners - which works fine. However, when the window is closed I need the method to return a String[] array; this is the part that is causing the problems...
I have added a simple return statement at the end of the method, but obviously Java doesn't wait for the action listeners and thinks that the method is complete once the action listeners have been added. So is there any way to "hold" a method, and then resume it when I am ready - or even, a different solution to my problem?
Thanks in Advance
Use a modal JDialog or a JOptionPane instead. The code that opened it will pause at that point - until the modal component is dismissed from the screen.
try it with a WindowListener so when you close the window, you can send your array
as example:
public class YourClass{
...
window.addWindowListener(new NameOfListener());
...
class NameOfListener() extends WindowAdapter{
#Override
public void windowClosed(final WindowEvent e)
{
// send your array
anInstanceYouWish.setArrayXY(yourStringArray);
}
}
}
You can add a WindowListener to the JFrame instance and override the windowClosing(WindowEvent e) method. And therein, you can implement your own behavior.

error in running a simple swing program

i just started learning swings. And thought of trying out a simple program, but i can't run it.
import java.awt.*;
import javax.swing.*;
class MyDrawPanel extends JPanel
{
public void paintComponent(Graphics g)
{
g.setColor(Color.orange);
g.fillRect(20,50,100,100);
}
}
I am getting the following error:
Exception in thread "main" java.lang.NoSuchMethodError: main
My Question: Do we need to have a main method in every class we want to run? Can't JVM run any class which doesnt have a main method. Here i don't require a main class i think, cuz this paintComponent method should be called by the system, right?
P.S: I am using plain vanilla cmd to compile and run.
java is rather simple, when you give it a class file it will load it and try execute a program. Java programs are defined to start in the "public static void main(String... args)" method. So a class file missing this function has no valid entry point for a program.
To make java call your paintComponent() method you have to add an instance of your class to a toplevel container like JFrame or for web applications an JApplet. (Applets don't use a main method as they are executed as part of a web page and not a standalone app.)
Example:
import javax.swing.*
public class MyDrawPanel{
public static void main(String... args)
{
JFrame frame = new JFrame(200,200);//A window with 200x200 pixel
MyDrawPanel mdp = new MyDrawPanel();//Panel instance
frame.add(mdp);//Add the panel to the window
frame.setVisible(true);//Display all
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when the window is closed
}
}
As vodkhang said, you need a "main" method. Make sure it looks just like this:
public static void main(String[] args)
{
// your code here.
// this example will use your panel:
// create a new MyDrawPanel
MyDrawPanel panel = new MyDrawPanel();
// create a frame to put it in
JFrame f = new JFrame("Test Frame");
f.getContentPane().add(panel);
// make sure closing the frame ends this application
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// show the frame
f.setSize(100,100);
f.setVisible(true);
}
Yes, every Java program that you want to run needs a main method with exactly this signature:
public static void main(String[] args)
You can run java code from within other systems (like web servers and etc without a "main") but to simply run it, the main is the entry point. Put it where-ever you want to start a program running.
When running, make sure you get the class name right to help it find your main method. In your case, if you are running java by hand in the same directory as your MyDrawPanel.class file you would do this:
java -cp . MyDrawPanel
If you are running from inside a developer tool, then it will provide a way to run the class you are looking at.
Do we need to have a main method in
every class we want to run?
You need a class with a main method to start a JVM.
Can't JVM run any class which doesnt have a main method.
Not initially.
Here i don't require a main class i think, cuz this paintComponent method should be called by the system, right?
Wrong. It's true that the paintComponent() method will eventually be called by "the system", specifically the Swing Event Dispatch Thread. But that needs to be started first, which happens implicitly when you create a window and make it visible. And that in turn can only happen in a main method.
You need a main method in the class that you want to run the program for. It is mandatory. How can the JVM know which method they should call to start if you have multiple methods. They can guess but most of the time, the guess may go wrong. So, provide a simple main method will help

Categories