Rmi inner class extending Applet is it possible
I have created four classes for my RMI program
1>hellointerface
2>helloserver
3>register
4>helloclient
hellointerface has only one Abstract Method
public String sayhello()throws java.rmi.RemoteException;
The problem is with my helloserverclass. my helloserver class needs to extend UnicastRemoteObject however i want to do it by using
UnicastRemoteObject.exportObject(this);
There is no problem with the coplilation of code of this class.
classregister is what getting effected if i use exportObject(this)function.
the problem is the command prompt where i run java register
appers like this
Object created
Object ready for use
and than the register stop running .The same console is ready for
running other Program where as in the case of Rmi the class that register the object using rebind() method must keep on running in the dos prompt
my register class looks something like this
try
helloserver object=new helloserver()
System.out.println("Object created");
Naming.rebind("/helloserver",object);
System.out.println("Object ready for use");
my server side code is something like this
public class helloserver implements hellointerface
public helloserver throws java.rmi.RemoteException
UnicastRemoteObject.exportObject(this);
//and the only method defined is as follows
public String sayhello()throws java.rmi.RemoteException
return "Thank u for reading this the current System time is "+new Date();
the client side is having a Applet which display this Message
I know this is a simple program but plz help me out
Thank u
Sorry xHacker I didn't see this one before but it is another multi-post of
http://forum.java.sun.com/thread.jspa?threadID=644864&tstart=0
Similar Messages
-
Inner Class extending the outer class
Could anyone explain this code to me? It can compile and run. Could anyone tell me what the class Main.Inner.Inner is? What members does it consists of? How the compiler manage to build such a class?
public class Main {
public static class Inner extends Main {
public static void main(String[] args) {
System.out.println("Hello, world.");
}By the way, it's not really an inner class, because it's static. It's just a nested class.
You might want to have a nested class extend its enclosing class if, maybe, you wanted to delegate to subclasses and didn't want to create a lot of extra source code files, which might make sense if the nested subclasses were really small.
public abstract class Animal {
public abstract void makeSound();
private Animal() {} // can't be directly instantiated
private static class Dog extends Animal {
public void makeSound() { System.out.println("woof"); }
private static class Cat extends Animal {
public void makeSound() { System.out.println("meow"); }
private static class Zebra extends Animal {
public void makeSound() { System.out.println("i am a zebra"); }
public static Animal get(String desc) {
if ("fetches sticks".equals(desc)) {
return new Dog();
if ("hunts mice".equals(desc)) {
return new Cat();
if ("stripey horse".equals(desc)) {
return new Zebra();
return null;
public class AnimalTest {
public static void main(String... argv) {
Animal a = Animal.get("fetches sticks");
a.makeSound();
} -
Can inner class satisfy our multiple inheritance limitation
i mean to say for eg
static inner class extending applet and outer class extending some
different classhello that was just a eg
if i go in deep its like this the remote method that i m having in the outer class is having a string i declare a globle varial of type string store the the String from remote method
(remember the outer class i m taking is the serverside code which extends Unicastremote object
and it has a inner class extending applet)
that is being passed by the client to the remote method display the string using repaint or paint method
this will b like a client chating to server
did u get it; -
Application & JApplet - Inner Classes
Hi,
I am having problems understanding the purpose of Inner Classes.
1. Is purpose of inner class in an Application to take care of what init method
takes care of in a JApplet. I believe init method in JApplet brings up the browser and
xecutes statements in init()?
2. Is it possible to write the enclosed Application without using an Inner Class?
If so, can someone please show me how?
3. Is it possible to write the enclosed JApplet using an inner Class?
If so, can someone please show me how?
Maybe if I see how an Application and JApplet are written with and without inner classes, this may help me understand.
Thank you.
//APPLICATION USING AN INNER CLASS
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//outerclass
public class InnerTest extends JFrame
private JTextField numField, sumField;
private int sum = 0;
public InnerTest()
super("Inner Test");
Container c = getContentPane();
c.setLayout(new FlowLayout());
ActionEventHandler handler = new ActionEventHandler();
numField = new JTextField(10);
sumField = new JTextField(10);
numField.addActionListener(handler);
c.add(numField);
c.add(sumField);
public static void main(String args[])
InnerTest win = new InnerTest();
win.setSize(400, 140);
win.show();
//Innerclass
private class ActionEventHandler implements ActionListener
public void actionPerformed(ActionEvent e)
sum += Integer.parseInt(numField.getText()); // access to sum and numField
numField.setText("");
sumField.setText(Integer.toString(sum));
JAPPLET
Below is modification of above code to a JApplet
without using inner class. I have CAPITALIZED MODIFICATIONS.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InnerTest extends JAPPLET
private JTextField numField, sumField;
private int sum = 0;
public VOID INIT()
super("Inner Test");
Container c = getContentPane();
c.setLayout(new FlowLayout());
ActionEventHandler handler = new ActionEventHandler();
numField = new JTextField(10);
sumField = new JTextField(10);
numField.addActionListener(THIS);
c.add(numField);
c.add(sumField);
public void actionPerformed(ActionEvent e)
sum += Integer.parseInt(numField.getText()); // access to sum and numField
numField.setText("");
sumField.setText(Integer.toString(sum));1. Is purpose of inner class in an Application to
take care of what init method
takes care of in a JApplet. I believe init method in
JApplet brings up the browser and
xecutes statements in init()?No. The init() method of an applet is similar to the constructor for an application. It is used to initialize data for the applet, the same data you will initialize in the constructor of the application.
>
2. Is it possible to write the enclosed Application
without using an Inner Class?Yes it is possible. The power of an inner class is that is has access even to private member variables of the enclosing class. In your case the event handler has access to the private variables: numField and sumField. If you do not use an inner class you have to pass a reference to your frame in the event handler's constructor and access the variables through that reference. But in this case you do not have access to private variables. So you must provide methods to access those variables or you must change theri visibility.
ActionEventHandler handler = new ActionEventHandler(this);Provide accessor methods in InnerTest class:
public String getTextString(){
return numField.getText();
public void setTextString(String text){
numField.setText(text);
}As for the applet it works just as your application in this case, you can use inner classes or not but with the same restrictions.
I hope you can understand what I tried to explain. -
Hi,
I have an applet with inner classes (the applet is contained in a single .java file). When I compile the applet, a number of *$*.class files are created for the inner classes. However, a friend of mine compiles the same .java file and he gets a single .class file. He can't see any files corresponding to the inner classes. My compiler is version 1.4.0, his is 1.4.2. Can you suggest how my friend can generate the *$*.class files corresponding to the inner classes?
Thanks for your help.
Miguel
PS If the .jar file does not contain the *$*.class files, then appletviewer can't find the inner classes.Let me try again. My friend gets a single .class file.
If he invokes the applet like this:
<APPLet CODE="myapplet.class" WIDTH=100 HEIGHT=100>
he has no problems at all.Because all the necessary files are there. Including the inner class files. Why he doesn't see them is another problem.
However, if he puts his class file in myjar.jar and
invokes the applet like this:
<APPLet CODE="myapplet.class"
ARCHIVE="myjar.jar"
WIDTH=100 HEIGHT=100>
then his inner classes are not found by appletviewer.Because he didn't put the inner class files in the jar. Why he didn't put them is another problem.
There is abosolutely no other explanation I can see. -
Inner class inside a method - how does it access method's local variable?
hello All:
I've learnt that, an inner class, if defined inside a method, it can access the method's local variables, only when they are defined as "final".
Anyone can help explain the rationale behind it?
Thanks a lot!
SwayfathomBoat wrote:
In java, everything is about pass-by-reference.
Wrong! Nothing in Java is ever pass-by-reference.
Java uses pass-by-value everywhere.
It makes sense to me if the reason of enforcing a variable to be "final" is to prevent it being messed up.No, the reason is that a copy is made and if the variable weren't final then it could change later on and the developer could be confused because his inner class didn't "see" that change.
The variable being final prevents that scenario.
However, if a copy of the variable is made inside the inner class, i dont see how possible it could affect variables outside of class?Such a copy is made, but the language designers wanted to hide that fact from the developer. By forcing all accessed variables to be declared final the developer has no way to realize that he's actually working on a copy. -
Extending a member inner class
I have a class
public class A{
class InnerClassB{
Now the question is how to extend the inner class would it be
class ExtendingInnerClassB extends A.B{
or else?
I am not sure anybody knows?Regarding inheritance from inner classes you must define your constructor:
public ExtendedInnerClass(EnclosingClass EC) { EC.super(); }
why?????
well
1. Where is the handle? The handle is an internal thing which is designed to accept the enclosing class. It is something which is not in the programmer's control. when there is an inner class, it is natural that the inner class cannot exist without its outer class. And that is the reason why the instantiation of an inner class is done using new OuterClass().new Innerclass(). U can see that the innerClass object is created based on the outer class object (assuming that the inner Class is not static). I hope that this is clear. Now .. the whole point is how does the compiler know that the Outerclass is the enclosing class? When the above line is compiled, the tricky handle in the inner class is assigned to the Outer class. So any reference henceforth is made based on this handle.
2. In the Inherited Inner class, there is no way to assoicate the handle in the above manner. Hence we are forcing by calling the super().
3 Otherwise why not simply create with: new InheritedInnerClass(EnclosingClass)? This is not possible. What if the inherited inner class needs a constructor in the above manner. That is assume that there is a class A. Then if the Inner Class needs the constructor to be InnerClass(A a, EnclosingClass b) for some other purpose, then what judgement can the compiler take? So that answers the question <b>Can't the compiler compile the inherited inner class assuming a handle to the enclosing class and then force an instance to be created using the EnclosingClass.new syntax?</b> Becuase in this case it cant go by any assumption.
4. Maybe the compiler designers can make some change such that the inherited inner class should have all its constructors beginning with the enclosing object and there should be atleast one constructor. But somehow I feel that it is too much of asking. -
Cann't extend a inner class where as can Implement a nested Interface
i cann't extend a inner class in some other outer class . Where as i can implement the nested Interface in some other class. Why????
for example:-
class ABC
class Inner
/* class body */
interface TempInterface
/* interfacebody */
class OuterClass
class InnerTwo extends ABC.inner //(line 1)Will give error
class InnerTwo implements ABC.TempInterface //(line 2)Will run fine
the line 1 is going to give compilation error i.e not in the scope but the line 2 will run fine .
Both of the things are in the same class but giving 2 other results.
I am not getting sufficient reasons for it.
Can any one help me????
Reagrds
ArunabhAs far as the language is concerned, the classonly
exists in the context of an instance of theenclosing
class.This still exhibits a class/object confusion to me.
It should be 'instance only exists ...' or 'instance
can only exist'. The class only exists in the
scope of the enclosing class, but this is another
issue.I'm not following what you're saying. The second sentence sounds like you're disagreeing with me. The last sentence sounds like you're agreeing with me.
A non-static nested class is an instance member, just like an instance method or instance variable. As such, as far as the language is concerned, that class only exists in the context of an instance of the enlcosing class.It's not just instances of the nested class--its the class definition itself that only exists within the context of an instance of the enclosing class. That's why you have to do anEclosingIntstance.NestedClass and can't do EnclosingClass.NestedClass. -
Possible have the an inner class named the same as an outer class?
Is there some workaround for this issue? I have some code generated by JAXB that won't compile because of a situation like this.
public class Class1 {
public Class1() { }
public static class Quantity {
public Quantity() { }
public static class Year {
public Year() { }
public static class Quantity {
public Quantity() { }
}When I remove the inner-most Quantity class, the compiler creates:
Class1.class
Class1$Quantity.class
Class1$Quantity.Year.classTry a different name for the inner class. I'm sure there is no dearth of names.
-
Problem with constructor of inner class.
Hi everybody!
I have an applet which loads images from a database.
i want to draw the images in a textarea, so i wrote an inner class, which extends textarea and overrides the paint method.
but everytime i try to disply the applet in the browser this happens:
java.lang.NoClassDefFoundError: WohnungSuchenApplet$Malfl�che
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:1590)
at java.lang.Class.getConstructor0(Class.java:1762)
at java.lang.Class.newInstance0(Class.java:276)
at java.lang.Class.newInstance(Class.java:259)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:567)
at sun.plugin.AppletViewer.createApplet(AppletViewer.java:1778)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:496)
at sun.applet.AppletPanel.run(AppletPanel.java:293)
at java.lang.Thread.run(Thread.java:536)
so my class has no own constructor, it just has the paint method overwritten.
my class looks like this:
public class Malfl�che extends javax.swing.JTextArea{
public void paint(Graphics g){
Color grey=new Color(220,220,220);
g.drawImage(img,10,10,null);
how should a constructor for this class look like?
sorry i am quite new to this, so i really dont have a clue!
my class does not have any attributes or requires any so it doesnt need a constructor, doesnt it?
thanks a lot
timFirst off, unlike regular classes, inner classes can be declared public, private, protected, and default.
Secondly, why are you using the JTextArea to display an image, why not use a JLabel, which takes an Image object as its constructor.
Thirdly, when you drew your image you did not give it a width and height
g.drawImage(img, 0,0, img.getWidth(null), img.getHeight(null), null);
otherwise it will make your image 1 X 1 pixels. not big enough to see. -
Null pointer exception with inner class
Hi everyone,
I've written an applet that is an animation of a wheel turning. The animation is drawn on a customised JPanel which is an inner class called animateArea. The main class is called Rotary. It runs fine when I run it from JBuilder in the Applet Viewer. However when I try to open the html in internet explorer it gives me null pointer exceptions like the following:
java.lang.NullPointerException
at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2761)
at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2722)
at Rotary$animateArea.paintComponent(Rotary.java:251)
at javax.swing.JComponent.paint(JComponent.java:808)
at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4771)
at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)
at javax.swing.JComponent._paintImmediately(JComponent.java:4668)
at javax.swing.JComponent.paintImmediately(JComponent.java:4477)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:448)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
Do inner classes have to be compiled seperately or anything?
Thanks a million for you time,
CurtinRI think that I am using the Java plugin ( Its a computer in college so I'm not certain but I just tried running an applet from the Swing tutorial and it worked)
Its an image of a rotating wheel and in each sector of the wheel is the name of a person - when you click on the sector it goes red and the email window should come up (that doesn't work yet though). The stop and play buttons stop or start the animation. It is started by default.
This is the code for the applet:
import java.applet.*;
import javax.swing.JApplet;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.image.*;
import java.util.StringTokenizer;
import java.net.*;
public class Rotary extends JApplet implements ActionListener, MouseListener
public boolean rotating;
private Timer timer;
private int delay = 1000;
private AffineTransform transform;
private JTextArea txtTest; //temp
private Container c;
private animateArea wheelPanel;
private JButton btPlay, btStop;
private BoxLayout layout;
private JPanel btPanel;
public Image wheel;
public int currentSector;
public String members[];
public int [][]coordsX, coordsY; //stores sector no. and x or y coordinates for that point
final int TOTAL_SECTORS= 48;
//creates polygon array - each polygon represents a sector on wheel
public Polygon polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48;
public Polygon polySectors[]={polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48};
public void init()
members = new String[TOTAL_SECTORS];
coordsX= new int[TOTAL_SECTORS][4];
coordsY= new int[TOTAL_SECTORS][4];
currentSector = -1;
rotating = true;
transform = new AffineTransform();
//***********************************Create GUI**************************
wheelPanel = new animateArea(); //create a canvas where the animation will be displayed
wheelPanel.setSize(600,580);
wheelPanel.setBackground(Color.yellow);
btPanel = new JPanel(); //create a panel for the buttons
btPanel.setLayout(new BoxLayout(btPanel,BoxLayout.Y_AXIS));
btPanel.setBackground(Color.blue);
btPanel.setMaximumSize(new Dimension(30,580));
btPanel.setMinimumSize(new Dimension(30,580));
btPlay = new JButton("Play");
btStop = new JButton("Stop");
//txtTest = new JTextArea(5,5); //temp
btPanel.add(btPlay);
btPanel.add(btStop);
// btPanel.add(txtTest); //temp
c = getContentPane();
layout = new BoxLayout(c,layout.X_AXIS);
c.setLayout(layout);
c.add(wheelPanel); //add panel and animate canvas to the applet
c.add(btPanel);
wheel = getImage(getDocumentBase(),"rotary2.gif");
getParameters();
for(int k = 0; k <TOTAL_SECTORS; k++)
polySectors[k] = new Polygon();
for(int n= 0; n<4; n++)
polySectors[k].addPoint(coordsX[k][n],coordsY[k][n]);
btPlay.addActionListener(this);
btStop.addActionListener(this);
wheelPanel.addMouseListener(this);
startAnimation();
public void mouseClicked(MouseEvent e)
if (rotating == false) //user can only hightlight a sector when wheel is not rotating
for(int h= 0; h<TOTAL_SECTORS; h++)
if(polySectors[h].contains(e.getX(),e.getY()))
currentSector = h;
wheelPanel.repaint();
email();
public void mouseExited(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void email()
try
URL rotaryMail = new URL("mailto:[email protected]");
getAppletContext().showDocument(rotaryMail);
catch(MalformedURLException mue)
System.out.println("bad url!");
public void getParameters()
StringTokenizer stSector;
String parCoords;
for(int i = 0; i <TOTAL_SECTORS; i++)
{ //put member names in applet parameter list into an array
members[i] = getParameter("member"+i);
//separate coordinate string and store coordinates in 2 arrays
parCoords=getParameter("sector"+i);
stSector = new StringTokenizer(parCoords, ",");
for(int j = 0; j<4; j++)
coordsX[i][j] = Integer.parseInt(stSector.nextToken());
coordsY[i][j] = Integer.parseInt(stSector.nextToken());
public void actionPerformed(ActionEvent e)
wheelPanel.repaint(); //repaint when timer event occurs
if (e.getActionCommand()=="Stop")
stopAnimation();
else if(e.getActionCommand()=="Play")
startAnimation();
public void startAnimation()
if(timer == null)
timer = new Timer(delay,this);
timer.start();
else if(!timer.isRunning())
timer.restart();
Thanks so much for your help! -
Calling functions of the inner class in .java code file
Hello,
I created a .java code file in Visual J#.Net and converted it into
the application by adding the "public static void main(String args[])"
function.
I have created the two classes one extends from Applet, and the other
extends from Frame. The class which I inherited from the Frame class becomes
the inner class of the class extended from the Applet. Now How do I
call the functions of the class extended from Frame class - MenuBarFrame
class. the outline code is
public class menu_show extends Applet
------init , paint action function---------
public class MenuBarFrame extends Frame
paint,action function for Menu
public static void main(String args[])
applet class instance is created
instance of frame is created
Menu , MenuBar, MenuItem instance is created
and all these objects added
I have Created MenuBarFrame class instance as
Object x= new menu_show().new MenuBarFrame
????? How to call the functions such as action of MenuBarFrame class - what
should be its parameters??????
}Here's how I would do it:
interface Operation {
public int op(int y);
class X {
private int x;
public X(int x) {
this.x = x;
private class Y implements Operation {
public int op(int y) {
return x+y;
public Operation createOperation() {
return new Y();
public static void main(String[] args) {
X app = new X(17);
Operation f = app.createOperation();
System.out.println(f.op(-11));
}Your code, however, has some serious "issues". You typically don't
instantiate an applet class -- that's the job of the applet viewer or Java plugin
your browser is using. If you instantiate the applet directly, you're going
to have to supply it an AppletStub. Do you really want to go that way?
Again, use an applet viewer or browser, or better yet, why write applets at all? -
Accessing method in an inner class
I have a class, which has an Inner Class, which is an extension of AbstractTableModel. The extended TableModel class has a new method, so it looks something like this;
public class TheOuterClass
JTable aTable
TableModel theTableModel
public initTable
theTableModel = new MyTableModel();
public TableModel getModel()
return theTableModel;
private class MyTableModel extends AbstractTableModel
public void myTableModelMethod()
}So, the idea here is that I have a class that has a table referenced by 'aTable', which uses MyTableModel as the class for it's table model. I have only implemented the basics here. The class also has a method called getModel(), so from a reference to 'TheOuterClass', I can access the table model.
Now, say I have a reference to TheOuterClass called toc, and I want to access my new method in the table model;
toc.getModel().myTableModelMethod()The above won't work, because getModel() returns a type of TableModel.
My question then is how do I cast this to the correct type, so I can access the method 'myTableMethod()'?
Is for example, the following a legal possibility, because I cannot seem to make it work;
(toc.getModel().getClass())(toc.getModel()).myTableMethod();The quick fix, I guess is to correct getModel in TheOuterClass, so it returns the correct type, but I am hoping to not do this. (This is part of a larger piece of code obviously, and TheOuterClass is in reality a bean, and I don't wnat to disturb anymore than I have to).
Any suggestions / ideas would be gratefully appreciatedYou are of course both correct, the class is private, should have spotted that! Doh. Also correct in that this is 'not the most elegant design', but you know the way it is you have to work with what you are given.
So, I changed the class to public....
What I had hoped is that the following would work
((toc.getModel().getClass())(toc.getModel())).myTableMethod()get a reference to the table model
(toc.getModel())cast it to the correct type (not sure if this is a valid way to cast??)
((toc.getModel().getClass())(toc.getModel()))then call the method.
This does not compile, it complains about a missing ')', and I'm sure they are all there. My question here then is, Is this a valid way to cast, now that the inner class is public?
As to why I want to do this, then some explanation is required;
The table model holds a Vector with all the data in it, some which is not actually in the table (it was originally written this way). My additional method myTableMethod() is intended to help access the data that is not shown in the table.
Coming back to kajbj's point of creating an interface, I presume what is being suggested is that I create a public interface with the myTableMethod() in it, and make myTableModel implement this interface. Since the interface is public, then I can cast to that. Is this what you meant?
Thanks for your help so far -
My question pertains to the code at the bottom of this post.
I don't understand why the compiler doesn't give an error for the line below. Why would it let you refer to something inside the class (in this case I'm referring to ClassWithInnerClass.MyInnerClass) unless it were static?
ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();To illustrate why I'm asking, I created 2 ints ("regularInt" and "staticInt") inside class "ClassWithInnerClass". The compiler let me set the value of "staticInt" from within main whereas it wouldn't let me do so w/ "regularInt" (which is why I commented that line out). Don't get me wrong though - I understand the reasons why the compiler behaves as it does for "regularInt" and "staticInt". I understand that a static variable can be accessed without instantiating a class (and that there's only 1 created no matter how many classes are instantiated). I also understand that, to access a non-static variable, you need to instantiate a class. My question arises only because of trying to extend that logic to MyInnerClass.
I can already take a guess that the answer is going to be something like, "the reason it works this way is because class 'MyInnerClass' is just a declaration NOT a definiton". I guess I just want confirmation of this and, if possible, some reasoning behind this logic.
HERE'S THE CODE...
class CreateInnerClasses {
public static void main (String args[]) {
ClassWithInnerClass cwic = new ClassWithInnerClass();
ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();
//ClassWithInnerClass.regularInt = 5;
ClassWithInnerClass.staticInt = 10;
mic.printIt();
class ClassWithInnerClass {
public int regularInt ;
static public int staticInt;
class MyInnerClass {
void printIt() {
System.out.println("Inside ClassWithInnerClass.myInnerClass");
MyInnerClass retMyInnerClass () {
return new MyInnerClass();The line ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();is accepted because the name of the inner class is ClassWithInnerClass.MyInnerClass. This has nothing to do with accessing fields even though the syntax is similar.
On the other hand, the line SomeClassWithAnInnerClass.InnerClass ic = new SomeClassWithAnInnerClass.InnerClass();is not accepted because the nested class SomeClassWithAnInnerClass.InnerClass is not static: you must have an instance of the outer class available. The correct syntax for calling the constructor of the inner class would be Outer.Inner instance = outerInstance.new Inner();In this case you could write: ClassWithInnerClass.MyInnerClass mic = new SomeClassWithAnInnerClass() . new InnerClass();
// OR:
ClassWithInnerClass.MyInnerClass mic = cwic . new InnerClass();The Java tutorial has a pretty good explanation on nested classes:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html -
I'm trying to complete a "turn the lightbulb on and off" program, but when I try to draw circle2 in the
ButtonListener class I get an error message cannot find symbol. This is in reference to the Graphics
variable "page" created in the paintComponent method below. Shouldn't the inner class, private or
public inherit all data variables including objects from the parent class, in this case, the Bulb class? The code is below.
By the way, this IS NOT a school assignment so any help would be appreciated. I'm just trying to learn
this language.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Bulb extends JPanel
private JButton push;
private Circle circle, circle2;
private final int DIAMETER = 100;
private final int X = 10;
private final int Y = 10;
public Bulb()
circle = new Circle(DIAMETER, Color.white, X,Y);
circle2 = new Circle(DIAMETER, Color.yellow, X, Y); // to separate class
push = new JButton("Turn on the Bulb");
push.addActionListener(new ButtonListener());
add(push);
setPreferredSize(new Dimension(500, 500));
setBackground(Color.black);
public void paintComponent(Graphics page)
super.paintComponent(page);
circle.draw(page);
private class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent event) //PROBLEM AREA. I GET ERROR MESSAGE STATING
// "CANNOT FIND SYMBOL" IN REFERENCE TO VARIABLE "PAGE."
// I THOUGHT THE INNER CLASS INHERITS ALL DATA FROM
// PARENT CLASS SUCH AS "PAGE."
circle2.draw(page);
}There are fields, which are associated with either a class or an object (and thus live in the heap in an object on the heap), and there are local variables, which are associated with methods and threads (i.e., a method invoked within a thread, and which thus live on the stack).
They're not the same thing.
You can't use a local variable in your paintComponent method in a different method.
Anyway you're designing your class wrong. Think model-view-controller. You have the model: a bunch of state and possibly behavior that represents the thing being seen, modified, and displayed. You have the view, which is how you see the model. And you have the controller, which modifies the model.
Your event handlers are part of the controller. They should change the model.
Your paintComponent method is part of the view.
So the event handlers should change some data, e.g., add a note that a circle should be displayed.
Then your paintComponent method should look at the data and act accordingly -- e.g., see that there's a circle to be displayed, and display it.
Maybe you are looking for
-
PHP 5.2.2 AND SAPRFC 1.4.1 5.2.2
Hello, i know, the same question i can find often in that Forum, but no answer will work on my system. <b><u>My Problem:</u></b> The "<i>php_saprfc.dll</i>" will not load. If i check with <i>extension_loaded ("saprfc")</i>, nothing will return. Also
-
Scanner on solaris HELP!!!!
I am running Solaris 10 6/06 and have installed the companion cd as well as someother things (Quake II, QEMU for example). I am trying to set up a USB HP office Jet 5500 all-in-one series. I set it up as a printer but i cant set up the scanner functi
-
Hi, After comming back from a vacation and turning on my iPod, I noticed that all of my songs were gone. I plugged it into my computer, and all of the songs did show up in iTunes. The "songs" playilst isn't showing up on my iPod even though the songs
-
Me: Macbook Pro 10.5.4 and time machine Mom: iMac 10.5.4 with new airport express Situation: Had Back to Mac up and running fine so I could take care of her machine. Then lightning strikes and nukes my mom's DSL box and ethernet card in her imac. She
-
I've lost my AC charger and normally wouldn't bother charging with the USB cord, but I had to. Anyway, I'm on a MacBook with all of the updates, iTunes 7.0.1 (haven't had problems with that yet), 20gb 4G iPod. When I try to charge with the USB cord,