I am beginning to learn Java and one thing is confusing me.
I have created a class PMO where I have created a TextField and put some text in it.
I have created another class PublicMethodObject where I have created the JFrame.
Now, I want to add the text set in TextField by using JFrame that I created in PublicMethodObject class.
How can this be possible?
class PMO{
public void J2(JTextField f1){
JTextField f= new JTextField();
f.setVisible(true);
String s="Hellow World";
f.setText(s);
return f;
}
}
public class PassMethodObject {
public PassMethodObject() {
JFrame a=new JFrame();
a.setVisible(true);
}
public static void main(String[] args) {
}
}
Your question is pretty confusing.
Maybe you meant using one class's method in another class because that is what it seems you are trying to do.
To do that you simply have to create the object of the first class inside second class and then use it for accessing the member variable and field(methods) of the first class. Unless it is static in that case you can call it directly using class's name.
example:-
access modifier Class A {
access modifier return type method(){};
}
access modifier Class B{
A ob = new A();
ob.method();
}
And of course, you have to take account of the access modifiers (public,protected,private,default) as well.
Related
To explain what I mean by this question I will use code examples below. Imagine you have this function.
private void fadeButton(JButton b, int timeToFade) {
//Fade code goes here
}
How would you implement this as a function which could be run like
JButton b = new JButton("Press Me");
b.fadeButton(20000);
Where fadeButton now looks like
private void fadeButton(int timeToFade) {
//Fade code goes here
}
Because the function is declared on the button itself.
Typically you create a derived class:
public JFadableButton extends JButton
This will contain the method private void fadeButton(int timeToFade).
Short answer is: you don't.
Longer answer:
You can't do that in Java directly (adding methods to a class outside of the source code of that class). That might be different in other languages, like Kotlin offers "something" like that.
In java, you have to make detours, for example by turning to the decorator pattern.
And just for the record: I didn't mention the simple "you can extend that class" because I read your question as "how do I add methods to JButton directly". But of course, creating your own class that extends JButton allows you to add methods; but of course, they only exist on objects of your derived class.
You could extend JButton with a new class, thus inheriting JButton's methods and adding the ability to add your own code:
public class FadingButton extends JButton {
//Constructors go here
private void fadeButton(int timeToFade) {
//Fade code goes here
}
}
You could also decorate the JButton with another class:
public class JButtonDecorator {
private JButton btn;
//Constructor here
private void fadeButton(int timeToFade) {
//Fade code goes here, hiding the held button
}
//getter and setter method for button
}
Or, if you want lots of different ways to affect your UI, you can make a utility class, similar to above:
//You could use a factory pattern to make this a singleton instead of having static methods
public abstract class UIUtils {
private UIUtils{} //Don't instantiate this class
public static void fadeComponent(JComponent toFade) {
//Fade code goes here
}
//Other static utility methods
}
Edit: Making use of these patterns. The extended class is self-explanatory and an example of simple inheritance, so it's just a matter of JButton btn = new FadingButton(); for example. Here are the others:
To use the decorator, instantiate it at the same scope as the button you're using now. For example:
JButton myButton = new JButton();
//Customize button and add to UI
JButtonDecorator jbDec = new JButtonDecorator(myButton);
jbDec.fadeButton(20000);
Although the button is a field of the decorator, it will otherwise behave normally in your UI. The decorator just wraps the class with useful methods such as the fadeButton method.
To use the utility class, there are two ways. One is two make an abstract class with static methods (as above), some consider it bad form but it's good for simple programs:
UIUtils.fadeComponent(myButton); //It's just that simple!
//The UIUtils class itself is never instantiated.
//All the methods are static, so no instances are needed.
Or if you want a more advanced method, make your utility class a singleton. This changes the utility class to this:
public class UIUtils {
UIUtils singleton;
private UIUtils{} //Don't instantiate this class publicly
public static UIUtils getInstance() {
if(singleton==null) //This is the first time the method is called
singleton = new UIUtils();
return singleton; //Return the one instance of UIUtils
}
public void fadeComponent(JComponent toFade) {
//Fade code goes here
}
//Other utility methods
}
Then you would declare your UIUtils object at class level to use across your UI:
UIUtils uiUtil = UIUtils.getInstance();
And somewhere in your code:
uiUtil.fadeComponent(myButton);
This pattern is more efficient with memory and is more object-oriented, but I don't personally find it very suitable for utility classes.
You can create a new class which extends JButton, and then add any method that could help you achieve what you want. But that's an exemple, there is many ways to achieve this.
Ps, don't set this method as private if you want to use it somewhere else than inside your class.
This is the simplest way I think think of. You have already got it. But just use this method:
private void fadeButton(int timeToFade) {
//Fade code goes here
}
This is assuming you already have the code for the fade, do you? I think this one is the one you should use. You don't need the button to be a parameter. When you want to call the method to fade the button, just put it in the ActionListener. So after you have the ActionListener for the button, do the following: btnName.fadeButton(timeToFade);
Here is how to code the ActionListener:
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
}
I have some code that I need to reuse in several Java apps. That code implements a GUI which in turn needs to access some static variables and methods from the calling class. Those variables and methods are always called the same in all of the apps. Is there a generic way to obtain a handle to the calling class in Java so the code for "someGUI" class can remain untouched and in fact come from the same source file for all the different apps?
Minimal working example:
import javax.swing.*;
class test {
static int variable = 123;
public static void main(String[] args) {
someGUI sg = new someGUI();
sg.setVisible(true);
}
}
class someGUI extends JFrame {
public someGUI() {
System.out.println(String.format("test.variable = %d", test.variable));
}
}
How can I "generify" the reference to "test" in test.variable to always just refer to the calling class? It's not the "super" class, at least using super.variable doesn't work.
Firstly I would advise against this approach since there are only brittle ways to implement it. You should parameterize SomeGUI with a parameter containing the values you need instead.
However, it is possible to do what you ask by examining the thread's stack trace and using reflection to access the static fields by name. For example like this:
class Test {
static int variable = 123;
public static void main(String[] args) throws Exception {
SomeGUI sg = new SomeGUI();
}
static class SomeGUI extends JFrame {
public SomeGUI() throws Exception {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
// stackTrace[0] is getStackTrace(), stackTrace[1] is SomeGUI(),
// stackTrace[2] is the point where our object is constructed.
StackTraceElement callingStackTraceElement = stackTrace[2];
String className = callingStackTraceElement.getClassName();
Class<?> c = Class.forName(className);
Field declaredField = c.getDeclaredField("variable");
Object value = declaredField.get(null);
System.out.println(String.format("test.variable = %d", value));
}
}
}
This will print test.variable = 123.
Obviously this is sensitive to renaming of the variables. It is also sensitive to dynamic proxies.
Also, it should be noted that you need to do this in the constructor. If you try to do this kind of lookup in other methods you can not find out how the instance was created.
There is no inheritance between somGUI and test,
Actual inheritance is there between someGUI and JFrame.
If you use super(), JVM tries to find 'variable' in JFrame, that is not what you wanted.
Use static methods setters & getters to access the 'variable' instead of direct accessing them.
Im new to Java and today i have a problem with my code when I trying to do ActionListener
My java class look like here:
public class exam{
private void createForm(){
...
JButton jbtn = new JButton("OK");
jbtn.addActionListener((ActionListener) this);
...
}
public static void main(String[] args){
exam ex = new exam();
ex.createForm();
}
public void ActionPerformed(ActionEvent ae){
//IDE show that no variable name "jbtn"
if (ae.getSource() == jbtn){
...
}
}
}
Your jbtn variable is declared within the createForm method. Java uses what are called "scoping rules" to make sure you don't accidentally use variables you don't mean to. By declaring jbtn in createForm, you are telling the Java compiler that you only want to use it in that method, and nowhere else. This is called a "local" variable (as in, it is local to the method).
You probably want to use a "member variable" (it is a member of the class). This is declared inside the class, but outside of any method. In your case, this looks like this:
public class exam{
JButton jbtn;
private void createForm(){
...
jbtn = new JButton("OK");
jbtn.addActionListener((ActionListener) this);
...
}
The declaration of the variable is now at the class level, and in createForm it is being referenced in the same way as in ActionPerformed.
This is a fairly basic concept in Java, so you might want to take a look at some Java tutorials that go over this ground. The official tutorial is a good place to start.
I'm trying to make a frame with a panel consisting of two buttons which reside at the bottom of the frame.
public class ControlledBall extends JPanel {
public static void main(String[] args) {
JFrame Frame = new Viewer();
Frame.setSize(1000, 500);
Frame.setTitle("Bouncing Ball");
Frame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
Frame.setVisible(true);
}
public class Viewer extends JFrame {
JButton buttonGo = new JButton("GO");
JButton buttonStop = new JButton("STOP");
JPanel aPanel = new JPanel();
public Viewer() {
aPanel.add(buttonGo);
aPanel.add(buttonStop);
this.add(aPanel, BorderLayout.SOUTH);
}
}
}
The problem here is this:
JFrame Frame = new Viewer();
It is telling me
ControlledBall.this cannot be referenced from a static context
How do I fix it?
You could do something like:
JFrame Frame = new ControlledBall().new Viewer();
instead of:
JFrame Frame = new Viewer();
But I'm not sure this is really what you want since ControlledBall is a JPanel...
Instances of non static inner classes hold a pointer to their enclosing object to be able to reference its members. See for example Java inner class and static nested class One side effect is that they cannot be instatiated from static methods, which have no relation to an actual instance of the enclosing class except by instatiating an intermediate object of your ControlledBall class.
PS: Another side effect to keep in mind (not so relevant for your use case) of this implicit this pointer is that it may cause resource leaks because it keeps the outer instance alive as long as the inner one lives.
You've created an public inner class inside the ControlledBall class, which is why you can't access it, as you don't have an instance of the ControlledBall class.
Guessing from the indentation and your code though, what you probably meant to do was create two seperate classes and instantiate the Viewer class from the main method of ControlledBall. To do that, move the Viewer class to its own file named Viewer.java and it should work.
The "main" method is static and when executed, its "containing" class might not yet been instantiated and so class Viewer might not yet exist. Since this example is apparently the program's entry point, "Viewer" most certainly does not yet exist.
There are many ways to resolve this, such as creating an instance of ControlledBall and then use that instance to create "Viewer".
It is my personal style to "get out of static" ASAP in a Java program by instantiating an instance of "main"s container and then running from there. I was taught that "main" is static so it exists to be called by the parent system and not much more use than that, I'm sure there are other opinions. Here is a brief example, which lacks many details:
public static void main(String[] args) {
// Pass 'args' to which ever method you prefer
ControlledBall app = new ControlledBall(args);
app.run(args);
}
private void run(String[] args) {
JFrame Frame = new Viewer();
}
I use 'run' because of Thread. I know many darts can be thrown at this, its just an example.
Make the inner class (Viewer) static
public static class Viewer extends JFrame
you can not acces non-static things from static methods
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.