Inner class problem
Hi.
I want 100 buttons to be displayed, 10 rows with 10 cols. To create all buttons I do a loop, and calls a function that creates and adds the buttons to the panel.
Here is the code sample.
<CODE>
// Here I adds the buttons
for (int i = 0; i < 10; i++) {
for (int y = 0; y < 10; y++) {
addButton(this, title,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
check(i,y);
},i,y,1,1);
// The function to add buttons
public void addButton(Container c, String title, ActionListener a, int x, int y, int w, int h) {
buildConstraints(gbco,y,x,w,h,0.0,0.0);
JButton b = new JButton();
b.addActionListener(a);
b.setText(title);
b.setSize(40,40);
Insets s = new Insets(0,0,0,0);
b.setMargin(s);
c.add(b,gbco);
</CODE>
The problem is that I want to access i, y (loop variables - wich represents the cordinates: i = rows and y = cols) in the actionPerformed() function (when I call check(i,y). But I cant access them, cause they are accessed within an inner class, and in order to do that, I have to declare i,y final. Wich I obvious cant do since they increase every time they loop.
So any suggestions on how to do this in another way, or how to get around this problem(eg. displaying 100 buttons, and when I click one, it should know what cordinates it has)?
one (of many) ways to do that is to make your own class. It would look something kinda like this...
public class smartJButton
private JButton jb;
private int row;
private int column;
public smartJButton( int r, int col, JButton button )
jb = button;
jb.addActionListener(new java.awt.event.ActionListener()
public void actionPerformed(java.awt.event.ActionEvent evt)
{ showCoordinates(); }
row = r;
column = col;
public void getCoordinates()
{ System.out.println("I am at row "+row+" and column "+column"); }
}
Similar Messages
-
EJB fails to compile - static inner class problem
I am using OC4J 9.0.4 and Sun JDK1.4.2 and EJBs fail to compile if they reference objects that contain static inner classes. However, they successfully compile under JDK1.4.1.
For example, I have a class like below:
public class ValueObject
public static class Key
private Key key;
private String value;
Any references to ValueObject.Key inside the EJB cause the EJB compiler to generate "ValueObject$Key" which is incorrect. JDK1.4.1 is more lenient than 1.4.2, and allows this error through.
Is there a way around this problem other than reverting to JDK1.4.1?
Regards,
AndyThe reason I don't want to move to JDK 1.4.1 is because of the memory leak in the StringBuffer.toString() method.
Is there anywhere I can submit this as a bug?
Regards,
Andy -
Inner Class Problem - I think...
Ok here's my problem. I have two classes, one is a servlet, the other implements Runnable. The first class called Job starts a new thread with using the second class, JobItem.
I created a simple object in the Job classes called lineItem. This is just a collection of Strings that make up a record of the Job run. I created in Job when I need to do things at the record level, and it works great. However, I want to use the same object in JobItem. I thought I could just create another a new instance of lineItem like this:
Job.listItem list = new Job.listItem();But I get an error: java.lang.NoSuchMethodError: com.jobconsole.web.Job$listItem: method <init>()V not foundI'm sure I am violating some OO rule, or am I really missing an init function? If so what do I put in said init function? Thanks.
RossThe method name <init> is a special method name that is used to refer to the a constructor for a class. If this is a runtime error (which it looks like it is) then what is happening is that some code is trying to call a constructor that doesn't exist. This generally happens when you make a change in one class and don't recompile classes that depend upon it. Try recompiling all of your source, and make sure there are no old copies of class files lying around.
-
Static inner class causes deployment on OC4J 10.1.2 to fail
Hi,
this issue has already been raised on OC4J 9.0.4 with J2SDK 1.4.2 (see EJB fails to compile - static inner class problem
Recap: When referencing static inner classes in an EJB, the deployment fails. During the generation of the wrapper classes, a signature <package>.<outer class>.<inner class> gets converted to <package>.<outer class>$<inner class>, which is syntactically wrong. While the Java 1.4.1 compiler kindly ignores this syntax error, its 1.4.2 counterpart complains - and fails.
@Oracle: When will this bug be fixed for OC4J 10.1.2?
Best regards,
HolgerHolger,
Don't static inner classes contradict the EJB specification?
In any case, in answer to Andy's question: If you wish to file this as a bug, you can do so via the MetaLink Web site.
[In fact, [i]MetaLink is your only option for submitting bugs for Oracle products -- as far as I know.]
Good Luck,
Avi. -
Problem with final variables and inner classes
variables accessed by inner classes need to be final. Else it gives compilation error. Such clases work finw from prompt. But when I try to run such classes through webstart it gives me error/exception for those final variables being accessed from inner class.
Is there any solution to this?
Exception is:
java.lang.ClassFormatError: com/icorbroker/fx/client/screens/batchorder/BatchOrderFrame$2 (Illegal Variable name " val$l_table")
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
at com.sun.jnlp.JNLPClassLoader.defineClass(Unknown Source)
at com.sun.jnlp.JNLPClassLoader.access$1(Unknown Source)
at com.sun.jnlp.JNLPClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
at com.icorbroker.fx.client.screens.batchorder.BatchOrderFrame.<init>(BatchOrderFrame.java:217)
at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.createView(BatchOrderViewController.java:150)
at com.icorbroker.fx.client.screens.RealTimeViewController.initialize(RealTimeViewController.java:23)
at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.<init>(BatchOrderViewController.java:62)
at com.icorbroker.fx.client.screens.displayelements.DisplayPanel$3.mousePressed(DisplayPanel.java:267)
at java.awt.Component.processMouseEvent(Component.java:5131)
at java.awt.Component.processEvent(Component.java:4931)
at java.awt.Container.processEvent(Container.java:1566)
at java.awt.Component.dispatchEventImpl(Component.java:3639)
at java.awt.Container.dispatchEventImpl(Container.java:1623)
at java.awt.Component.dispatchEvent(Component.java:3480)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3162)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
at java.awt.Container.dispatchEventImpl(Container.java:1609)
at java.awt.Window.dispatchEventImpl(Window.java:1590)
at java.awt.Component.dispatchEvent(Component.java:3480)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
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)I've also been having the same problem. The only work-around seems to be to slightly change the code, recompile & hope it works. See http://forum.java.sun.com/thread.jsp?forum=38&thread=372291
-
Problem with final variables and inner classes (JDK1.1.8)
When using JDK1.1.8, I came up with following:
public class Outer
protected final int i;
protected Inner inner = null;
public Outer(int value)
i = value;
inner = new Inner();
inner.foo();
protected class Inner
public void foo()
System.out.println(i);
}causing this:
Outer.java:6: Blank final variable 'i' may not have been initialized. It must be assigned a value in an initializer, or in every constructor.
public Outer(int value)
^
1 error
With JDK 1.3 this works just fine, as it does with 1.1.8 if
1) I don't use inner class, or
2) I assign the value in initializer, or
3) I leave the keyword final away.
and none of these is actually an option for me, neither using a newer JDK, if only there is another way to solve this.
Reasons why I am trying to do this:
1) I can't use a newer JDK
2) I want to be able to assign the variables value in constructor
3) I want to prevent anyone (including myself ;)) from changing the value in other parts of the class (yes, the code above is just to give you the idea, not the whole code)
4) I must be able to use inner classes
So, does anyone have a suggestion how to solve this problem of mine? Or can someone say that this is a JDK 1.1.8 feature, and that I just have to live with it? In that case, sticking to solution 3 is probably the best alternative here, at least for me (and hope that no-one will change the variables value). Or is it crappy planning..?You cannot use a final field if you do not
initialize it at the time of declaration. So yes,
your design is invalid.Sorry if I am being a bit too stubborn or something. :) I am just honestly a bit puzzled, since... If I cannot use a final field in an aforementioned situation, why does following work? (JDK 1.3.1 on Linux)
public class Outer {
protected final String str;
public Outer(String paramStr) {
str = paramStr;
Inner in = new Inner();
in.foo();
public void foo() {
System.out.println("Outer.foo(): " + str);
public static void main( String args[] ) {
String param = new String("This is test.");
Outer outer = new Outer(param);
outer.foo();
protected class Inner {
public void foo() {
System.out.println("Inner.foo(): " + str);
} producing the following:
[1:39] % javac Outer.java
[1:39] % java Outer
Inner.foo(): This is test.
Outer.foo(): This is test.
Is this then an "undocumented feature", working even though it shouldn't work?
However, I assume you could
get by with eliminating the final field and simply
passing the value directly to the Inner class's
constructor. if not, you'll have to rethink larger
aspects of your design.I guess this is the way it must be done.
Jussi -
Problems javadoc inner classes...
Hi all,
I have a problems documenting an inner class. I've implemented it this way:
* In file TestClass.java I have an inner class "class MainClass" (this is the "upper" class of the file)
* MainClass instantiates a TestClass (which in the file is declared as an inner class within MainClass: "public class TestClass").
When I try to document it I get the following error message:
"No public or protected classes found to document."
What do I have to do? I'm using "Standard Doclet version 1.4.1" and why I have to use the inner class is a matter of saving a copy of the entire object, and I think this is the only solution to it, so what do I do?? Do I declare the "outer" class in a different way?
Very pleased for all help!!
Best regards,
Anjelica* In file TestClass.java I have an inner class "class
MainClass" (this is the "upper" class of the file)
* MainClass instantiates a TestClass (which in the
file is declared as an inner class within MainClass:
"public class TestClass").So TestClass is an inner class of MainClass?? Then your file should be called MainClass.java.
Try if that helps. -
I ran into the following problems when I tried to read into an inner class:
This is my .jdo file
<?xml version="1.0"?>
<jdo>
<package name="com.globalrefund.jdo.mna">
<class name="Parameter$Syspar" objectid-class="SysparId">
<extension vendor-name="kodo" key="table" value="syspar"/>
<extension vendor-name="kodo" key="lock-column" value="none"/>
<extension vendor-name="kodo" key="class-column" value="none"/>
<field name="landescode" primary-key="true">
<extension vendor-name="kodo" key="data-column"
value="landescode"/>
</field>
<field name="waehrungscode">
<extension vendor-name="kodo" key="data-column"
value="waehrungscode"/>
</field>
</class>
</package>
</jdo>
1.) appidtool does not work for this inner class, I get this stack trace
C:\users\Bernhard\jbProject\refundManual>appidtool
src\com\globalrefund\jdo\mna\Parameter$Syspar.jdo
Generating an application id for type "class
com.globalrefund.jdo.mna.Parameter$Syspar"...
Exception in thread "main" java.lang.NullPointerException
at com.solarmetric.kodo.enhance.ApplicationIdTool.getFile(Unknown
Source)
at
com.solarmetric.kodo.enhance.ApplicationIdTool.writeApplicationId(Unknown
Source)
at
com.solarmetric.kodo.enhance.ApplicationIdTool.writeApplicationId(Unknown
Source)
at com.solarmetric.kodo.enhance.ApplicationIdTool.main(Unknown
Source)
2.) I tried to use a hand coded inner class as ID class, but id did not work
(is this not possible ?)
Exception in thread "main" java.lang.NoSuchMethodError:
com.globalrefund.jdo.mna.Parameter$SysparId: method <init>()V not found
at
com.globalrefund.jdo.mna.Parameter$Syspar.jdoNewObjectIdInstance(Parameter.j
ava)
at
javax.jdo.spi.JDOImplHelper.newObjectIdInstance(JDOImplHelper.java:166)
at com.solarmetric.kodo.util.ObjectIds.fromPKValues(Unknown Source)
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.createFromResultSet(
Unknown Source)
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager$2.getResultObject(Un
known Source)
at
com.solarmetric.kodo.impl.jdbc.runtime.LazyResultList.instantiateRow(Unknown
Source)
at com.solarmetric.kodo.impl.jdbc.runtime.LazyResultList.get(Unknown
Source)
at java.util.AbstractList$Itr.next(AbstractList.java:416)
at com.solarmetric.kodo.runtime.ResultListIterator.next(Unknown
Source)
at
com.solarmetric.kodo.impl.jdbc.runtime.ResultListFactory.createResultList(Un
known Source)
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.executeQuery(Unknown
Source)
at
com.solarmetric.kodo.impl.jdbc.runtime.JDBCQuery.executeQuery(Unknown
Source)
at com.solarmetric.kodo.query.QueryImpl.executeWithMap(Unknown
Source)
at com.solarmetric.kodo.query.QueryImpl.execute(Unknown Source)
at
com.solarmetric.kodo.query.QueryImpl$SynchronizedQuery.execute(Unknown
Source)
at com.globalrefund.jdo.mna.Parameter.<init>(Parameter.java:71)
3.) It worked after I moved the ID class into a separate class
Regards,
Bernhard1.) appidtool does not work for this inner class, I get this stack traceThis is a bug. It will be corrected in the final release of 2.3, due out
Real Soon Now. Thanks for catching this!
2.) I tried to use a hand coded inner class as ID class, but id did not work
(is this not possible ?)
Exception in thread "main" java.lang.NoSuchMethodError:
com.globalrefund.jdo.mna.Parameter$SysparId: method <init>()V not foundThis exception is saying that your application ID class does not have a
no-args constructor. Make sure the id class is a static inner class;
otherwise Java transparently adds a parent object parameter to each
constructor, and so the application id class will violoate the JDO constraint
of having a no-args constructor. -
Problems with inner classes in JasminXT
I hava problems with inner classes in JasminXT.
I wrote:
;This is outer class
.source Outer.j
.class Outer
.super SomeSuperClass
.method public createrInnerClass()V
.limit stack 10
.limit locals 10
;create a Inner object
new Outer$Inner
dup
invokenonvirtual Outer$Inner/<init>(LOuter;)V
;test function must print a Outer class name
invokevirtual Outer$Inner/testFunction ()V
.end method
;This is inner class
.source Outer$Inner.j
.class Outer$Inner
.super java/lang/Object
.field final this$0 LOuter;
;contructor
.method pubilc <init>(LOuter;)V
.limit stack 10
.limit locals 10
aload_0
invokenonvirtual Object/<init>()V
aload_0
aload_1
putfield Inner$Outer/this$0 LOuter;
return
.end method
;test
.method public testFunction ()V
.limit stack 10
.limit locals 10
;get out object
getstatic java/io/PrintStream/out java/io/PrintStream;
aload_0
invokevirtual java/lang/Object/getClass()java/lang/Class;
;now in stack Outer$Inner class
invokevirtual java/Class/getDeclaringClass()java/lang/Class;
;but now in stack null
invokevirtual java/io/PrintStream/print (Ljava/lang/Object;)V
.end methodI used dejasmin. Code was equal.
What I have to do? Why getDeclatingClass () returns null, but in dejasmin code
it returns Outer class?Outer$Inner naming convention is not used by JVM to get declaring class.
You need to have proper InnerClasses attribute (refer to http://java.sun.com/docs/books/vmspec/2nd-edition/html/ClassFile.doc.html#79996)
in the generated classes. Did you check using jclasslib or another class file viewer and verified that your .class files have proper InnerClasses attribute? -
Deployment problem: Inner class not included
Hi, All:
I am trying to deploy my Java application using JDeveloper 3.2. I was be able to successfully deployed it when I first designed the project, even some of the files also have inner classes. Now I have added some new inner classes to a public class and tried to re-deploy it. However how hard I tried (I have tried to rebuild the project, redefine the depoyment profile, even tried to add these class files directly through the advanced tab), the newly added inner class will not be able to be added to the deployed Jar file. I have checked the class files under myclass directory, and found all the inner class files are there, and I can run the application in JDeveloper without any problem. I wonder if there is any tricks to solve this problem. (Other than use the jar command).
Thanks,
PeterAlso, it's probably a good idea to name your packages different than your classesMoreover, common naming conventions dictate you should never even use capitals in your package names if I'm not mistaken. Whereas class names should always at least begin with a capital.
This will help prevent a lot of confusion, both for the developer and the IDE. ;-) -
Program Design Problem: Inner Class use verse interacting seperate classes?
i am designing a GUI based program that needs to have 2+ windows that interact with each other. In my original design there were just two windows: the World display, and the tile choser (this is for 2D map editing). Because there were only 2, I made them both inner classes of another class. The top level class's fields were how I got the two windows to interact.
Now I am adding more tile choser esque windows and it is getting very confusing and the amount of Fields is getting ridiculous and the whole thing isnt very OO.
I thought about splitting up the World Display window and the Tile Choser window into two different classes and just have multiple instances of the Tile Choser class for the additional windows.
The problem is the interaction. I could pass all of the variables that both classes require to constructers and set up lots and lots of get and set methods, but then that seems to destroy the whole idea of two classes. The whole project is getting really messy.
Any thoughts?
I know that was a jarbled explanation so just ask about any part that might be unclearCreate an object that represents the state being manipulated. The model.
Create methods to modify that data. Not getters/setters, but controllers. If it's a map, then maybe a method would be "addTown" or something. This represents the controller.
Create methods to render the data graphically. The views.
Pass this object to GUI widgets, or reference it from inner event handlers. -
Problem with Outer and Inner Classes....or better way?
Right now I'm trying to create an Inner class.
My .java file compiles ok, and I create my jar file too.
But when I try to instantiate the Inner class, it fails:
java.lang.NoClassDefFoundError: com/myco/vlXML/vlXML$vlDocument.
Here's the class code:
public class vlXML{
private ArrayList myDocList=new ArrayList(); //holds documents
public vlXML(){
private class vlDocument{
public vlDocument(){
//stuff goes here
public vlDocument vlDOC(){
return new vlDocument();
public void addDocument(){
vlXML xxx=new vlXML();
vlDocument myDoc=xxx.vlDOC();
myDocList.add(myDoc);
public int getNumDocs(){
return myDocList.size();
}Then, from a jsp page, I call:
vlXML junk1=new vlXML();
junk1.addDocument();...and get the error...
Can someone help me figure out why it's failing?
Thanks....You nailed it - thanks....(duh!)
While I have your attention, if you don't mind, I have another question.
I'm creating a Class (outer) that allows my users to write a specific XML file (according to my own schema).
Within the XML file, they can have multiple instances of certain tags, like "Document". "Document"s can have multiple fields.
Since I don't know how many "Documents" they may want, I was planning on using an Inner Class of "Document", and then simply letting them "add" as many as necessary (thus the original code posted here).
Does that seem like an efficient (logical/reasonable) methodology,
or is there there something better?
Thanks Again... -
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. -
Problems importing a class with inner class
Why can't I import a class so that I can use an (inner) static member class without naming the enclosing class. Put simply, I have:
file C:\MyJava\Test\A:
public class A {
public static class B { }
}file C:\MyJava\Test\C
import A.*;
public class C { }When I try to compile C (javac -classpath C:\MyJava\Test;. C.java) it fails with C.java:1: package A does not existClass A must be in a package if you wish to import it. If you want to use the inner class, just import somepackage.A. You could then refer to A.B...
HTH :o) -
Problem creating inner class for JTable panel in a class for an application
i want to create an inner class for a database application development.
but there is occuring exceptions & errors.i want to retrieve data & enter data also from many tables in a database.i want an urgent help for this plz.http://forum.java.sun.com/thread.jsp?forum=57&thread=271752
See this thread, please.
Maybe you are looking for
-
Did you know that now with iOS 7, you can reveal the Time Stamp of every text messages your receive in your Messages app?? All you have to do is, open a conversation, slide your finger across the screen from the right to the left, and on the right si
-
How do I pass a variable from edge animate to an external JS?
I need to pass a variable value from Edge Animate to an external JS file. How can I do it?
-
How to send e-mail with an attachment from remote database server.???
Hi All, I have tried the simple mail sending and with the attachment using UTL_SMTP. But the problem is , it is sending the mail with attachment of the file name i give, it takes and creates that file and sends as attachment not from the actual file
-
Saving email attachments into Photos
When I'm sent a picture as an email attachment I used to click at the top of the message and it would say "Export to iPhoto". How can I Export to Photos now? It still says "Export to iPhoto". I'm dragging and dropping each one at the moment. Grrrr!
-
Filling in and signing pdf files
Making an uncontested will.