Calling main method class from another java class - java

I have two java classes.One in which my GUI is written and the other class in which i have implemented an interface(call it class 2).My project starts from the main method of GUI.I want to send a string to my GUI class from the class 2 for displaying it in the Text area but nothing is happening.
As my main gui class is
public class GraphicalInterface extends javax.swing.JFrame{
//I have created a function over here for displaying string in text area
public void show1(String name)
{
jTextArea1.setText(name);
}
//buttons code
public static void main(String args[]) {
//code
}
}
I have created an object of this class in my class 2 like below
GraphicalInterface b=new GraphicalInterface();
b.show1("pear");// it does not allow me to write this statement
Please help me out that how can i call main method class from another java class.Thanks.

You may be trying to call this code outside of a constructor or method (or initializer block) and in Java, this can't be done. Instead call this code inside of a method or constructor.

I guess that you have a design problem in your project. Let me expain. You say you have a GUI class "GraphicalInterface" which holds the main method which is the starting point of an application in Java. You say you need to call the main method of this class in another class,
"your class 2". If so why isn't the place belonging to the "main method" of your application in which you try to call this GUI's main method. Call GUI's main method x(), let the place that you call x() belong to the main method.
If you need to operate on the GUI's fields in another classes and also keep the main method still there, then I suggest you to apply Singleton Pattern to your GUI class. In that way you
will be able to refer the only instance of your public singleton class everywhere in your application.
public class GraphicalInterface extends javax.swing.JFrame
{
public String textAreaContent;
public getX()( return textAreaContent;)
public setX(String s)( this.textAreaContent = s;)
public void show1()
{
jTextArea1.setText(this.getTextAreaContent());
}
public static void main(String args[])
{
//code
}
}
From your other class:
GraphicalInterface b=new GraphicalInterface();
b.setX("text area content");
b.show1();

No, the best solution is not to do this, and if you feel you must, it is likely because your design is somehow broken. Instead write your code so that your classes are true OOPs classes that interact in an intelligent way (low coupling, high cohesion), and to only need one main method.
Also, you state:
GraphicalInterface b=new GraphicalInterface();
b.show1("pear");// it does not allow me to write this statement
What do you mean by "it does not allow me to write this statement"? Does the Java compiler give a compilation error? Does the JVM throw an exception? Does the JVM reach out of your monitor and slap you in the face? Please let us know all the details necessary to be able to help you.

You need to create a method in class2 and call it from your main method.
Sample code class1
public class Test1 {
public void show(String ab){
System.out.println(ab);
}
public static void main(String[] args) {
Test2.Test2();
}
}
Above code i create a class Test1.java like your class1 and create a method with one parameter and call it from class2 method.
Sample code class2
public class Test2 {
static void Test2(){
new Test1().show("Pass String to class1 show method");
}
}
here you can pass your string value.

Related

Unsure as to why there is a class, interface or enum expected error?

I have just started creating this program and I am trying to make a method outside of the main class. I researched the error and it says there are too many curly brackets outside the main function.
I was just wondering if it was actually possible to have a public static function outside of a main class?
class NewMain {
public static void main(String[] args) {
}
}
public static void plusOne(){
}
Think of a class as a collection of code. You can have as many classes as you want. But you can not put code outside of a class and there is no reason you should want to.

Can we create an object of the class in which main function is defined in Java?

Is it possible to create object of class in which main method resides.I have been searching for this answer but I have been told that it depends on compiler some compiler will allow while others will not.Is that true?
Yes? The main method is just an entry point. The class is like any other, except it has an additional public static method. The main method is static and therefore not part of the instance of the object, but you shouldn't be using the main method anyway except for starting the program.
public class Scratchpad {
public static void main(String[] args) {
Scratchpad scratchpad = new Scratchpad();
scratchpad.someMethod();
}
public Scratchpad() {
}
private void someMethod() {
System.out.println("Non-static method prints");
}
}
Yes, you can create object for the class which has main method. There is no difference in this class and a class which don't have main method with respect to creating objects and using.

Main method empty?

I have a class that implements Runnable, but Eclipse needs a public static void main method in it. Is it ok if the main is completly empty?
public class Launcher implements Runnable{
private String message;
public Launcher(String message) {
this.message= message;
}
public static void main(String[] args) {
}
#Override
public void run() {
//My implementations
}
If you intend Launcher to be the main class of the application, the one you use to start it, the main method is needed and must do whatever should be done to start work.
If not, delete the main method. Eclipse does not require a main method unless you start the application by telling it to run the class. It will optionally generate one when creating a class, but that can be edited out if not needed.
No, the main method is the only method the compiler is searching for when looking where to start. Hence if you're main method is empty, nothing gets executed. At the very least add:
new Launcher("some string").run();
in the main method.

Java: How to update textArea from different class while a loop is running?

I am developing a little program to make reservations and I am stuck at how to update the textArea from a different class while I am doing some stuff in a loop ?
So for example I have this piece of code:
GUI class contains the very basic layout of GUI plus this method:
public class MyGUI extends JFrame implements ActionListener
{
public MyGUI()
{
...
}
....
public void setResultArea(String text)
{
resultArea.append(text);
}
}
Test class
public static void writeToTextArea()
{
while(true)
{
if(message = "Hello World")
...
modify text area
}
}
I look around but I couldn't find something related. Any ideas?
At the end of the day, your test class needs a reference to your MyGUI class. There are various ways to give this reference:
make a setter method in the test class which takes and stores a MyGUI.
give the test class a constructor which takes and stores a MyGUI.
This is not considering best-practices of software design. That means, since I don't know the whole of your project, I can't comment on the best approach.
Once the test class "has" an instance of MyGUI, you can call the "setResultArea" method on it from the place you've written "modify text area".

Call main method in a JButton

I would like to know, how to call the main method as it is in a JButton into a JFrame with an action performed, i mean, just press Compare Button & execute the code from main class (Main class is separate from JFrame code).
public static void main(String[]args){
Comparative comp = new Comparative();
if(comp.loadComparative(args[0])){
comp.compareDbs();
comp.sendEmail();
}
}
private void CompareActionPerformed(java.awt.event.ActionEvent evt) {
?????????????
}
If the main class is on the classpath you can use reflection :
private void CompareActionPerformed(java.awt.event.ActionEvent evt) {
MyMainClassToCall.main(myArgs);
}
If the class is located elsewhere, likely in a jar, you can certainly use an URLClassLoader to load the class which contains the main method, then use
myMainClass.getMethod("main", String[].class).invoke(null, myArgs);
You can just get the arguments you need and then call it using the name of the class where it is:
MainClass.main(args);
To give a complete answer we actually need to know what's the name of the class that contains that main method. Also, I'm struggling to understand such a weird requirement but I'll do my best to come up with a useful answer.
To invoke your main method you need to access it through the class that contains it, since it's a static method. You also need to provide an array of arguments mainly because it seems that your main method is using the first of the elements in the arguments array. So something like this would work:
private void CompareActionPerformed(java.awt.event.ActionEvent evt) {
String[] args = new String[] { "myparam" };
MainClass.main(args);
}
Now, said that, let me note that such an invocation of a main method is a very bad practice, you could achieve the same copying the contents of your main method into your event handler CompareActionPerformed. Or even better, creating a separate and independent class with an static method that performs the same that you need from your main method. Then invoke that new static method from your main class and from your event handler (assuming that all the code is accessible from the same class loader).
I think it's a bad practice , you should follow some design pattern , like MVC or something , when JVM starts it looks for the "main" method and start from there , the thing you can do before calling main method is putting some code in a static braces like ...
public class test {
static {
some code
}
public static void main(String[] args){
}
}
this code will be executed before the main
There is just one class, it is Comparative inside it's all the code incluing the main....

Categories