Referencing an inner swingworker class in a JPanel class...?

Hi,
I've got an inner swingworker class defined inside an extended JPanel (we'll call it middleJ) class. Basically the swingworker class runs off a filtered file chooser. I have a method in the JPanel class that instantiates the inner class and kicks off the swing worker (we'll call it kickOffSwing). Now if I instantiate middleJ in an outer class and call the kickOffSwing() method, that should run the filtered filechooser right? Is this the right way to go about running a lengthy background process inside a nested class structure, or is there a more organised way of doing things?
Cheers!

Never mind. Got it working fine! I often find the act of putting together a question helps focus on the task at hnad.

Similar Messages

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
    The code below is representative of my situation.
    public class ClassA
       ValueChecks vc = null;
       /** Creates a new instance of Main */
       public ClassA()
          System.out.println("ClassA Constructor");
          vc = new ValueChecks();
          vc.checkMaximum();
         // I want this to call the overridden method, but it does not, it seems to call
         // the method in this class. probably because vc belongs to this class
          this.vc.checkMinimum();
          this.myMethod();
       protected void myMethod()
          System.out.println("myMethod(SUPER)");
       protected class ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUPER)");
             return true;
          protected boolean checkMaximum()
             return false;
    }I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
    public class ClassASub extends ClassA
       public ClassAInner cias;
       /** Creates a new instance of Main */
       public ClassASub()
          System.out.println("ClassASub Constructor");
       protected void myMethod()
          System.out.println("myMethod(SUB)");
       protected class ValueChecks extends ClassA.ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUB)");
             return true;
    }The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
    I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.

    vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
    // I want this to call the overridden method, but it does not, it seems to > call
    // the method in this class. probably because vc belongs to this class
    this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
    And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original.

  • 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();
    }

  • Problem about JPanel Class

    Hello!I am a chinese Java2 learner.I want to ask you a question :
    Why do the instance variables of Jpanel class can not be declared as a array,just like JButton class?
    For example :
    JPanel[] pane = new JPanel[4];
    pane[0].add( ...);
    pane[1].add( ...);
    My program has passed the compile,but it can not run at all.Please experts give me an answer.Thank you very much!
    My E-mail:[email protected]

    what is the error message you get when you run the app.?

  • Can any one change this Applet into a class that extends Jpanel.....

    Hi,
    I need this applet as a class that extends JPanel, I will be very very thankful to you if any one kindly change this Applet code into a class that extends JApplet.
    I will be very thankful to you if some one can reserve few minutes & do this favor early.
    Thanks a lot for any help.
         My Pong Code
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    public class Class1 extends Applet implements Runnable
    {     private final int APPLET_WIDTH = 900;
         private final int APPLET_HEIGHT = 600;
         private int px = 15;
         private final int py = 560;
         private final int ph = 10;
         private final int pw = 75;
         private int old_px = px;
         private int bx = 450;
         private int by = 15;
         private final int bh = 20;
         private final int bw = 20;
         private int move_x = 2;
         private int move_y = 2;
         private boolean done = false;
         Thread t;
         private final int delay = 25;
         public void init()
         {     setBackground(Color.black);
              setSize(APPLET_WIDTH, APPLET_HEIGHT);
              requestFocus();
              addKeyListener(new DirectionKeyListener());
             (t = new Thread(this)).start();
         public void run()      {
        try      {     while((t == Thread.currentThread()) && (done == false))           {     
                   if ((bx < 15) || (bx > APPLET_WIDTH-30))                     move_x = -move_x;                                if ((by < 15) ||                    ((by > APPLET_HEIGHT-60)&&                     ((px<=bx)&&(bx<=px+pw))))
                        move_y = -move_y;
                   if (by > APPLET_HEIGHT)
                        done = true;
                                   bx = bx + move_x;
                   by = by + move_y;                                                repaint();
                   t.sleep(delay);
         catch(Exception e)      {}
         }//end run
         /*public void move_paddle(int amount)
              old_px = px;
              //if (amount > 0)
                //if (px <= APPLET_WIDTH-15)
                   px = px + amount;
              //else if (amount < 0)
               // if (px >= 15)
                   px = px + amount;
         public void paint(Graphics page)
              //     page.setColor(Color.black);
              //     page.drawRect(old_px, py, pw, ph);
                   page.setColor(Color.blue);
                   page.drawRect(px, py, pw, ph);
                   page.setColor(Color.white);
                   page.drawOval(bx, by, bw, bh);
                   if ((done == true) && (by > APPLET_HEIGHT))
                        page.drawString("LOSER!!!", APPLET_WIDTH/2, APPLET_HEIGHT/2);
                   else if (done == true)
                        page.drawString("Game Over, Man!", APPLET_WIDTH/2-10, APPLET_HEIGHT/2);
         private class DirectionKeyListener implements KeyListener               
              public void keyPressed (KeyEvent event)
                   switch (event.getKeyCode())
                   case KeyEvent.VK_LEFT:
                        old_px = px;
                        if (px >=15)
                             px -=10;
                        break;
                   case KeyEvent.VK_RIGHT:
                        old_px = px;
                        if (px+pw <= APPLET_WIDTH-15)
                             px += 10;
                        break;
                   case KeyEvent.VK_Q:
                        done = true;
                   default:
                   }  //end switch
                   repaint();
              }//end keyPressed
              public void keyTyped (KeyEvent event)
              public void keyReleased (KeyEvent event)
         }  //end class 
    }

    thank you sir for your advice.
    Its not like that I without any attempt, just past code here & asked for its conversion. I spent about 5 hours on it, can say spoil whole day but to no avail. You then just guide me, give some hint so that I do it. I will most probably wanted to do it by myself but asked for help when was just disappointed.
    I try to put all init() in default constructor of identical copy of this applet that extends JPanel. Problem.....ball tend to fell but pad not moving. Also out out was not getting ant color input. That was like my best effort.....other tried that I found by search like just do nothing only extend panel OR frame in spite of applet, start applet from within main of another class.... these are few I remember what I tried.
    I will be very very thankful to you if you can help/guide me how can I do it. Behavior of the Applet is like a normal PONG game with on pad controlled by arrow keys, & one ball colliding with walls of boundary & falling down.
    Thanks a lot again for your attention & time.

  • JEditorPane (or subclasses) and a class that extends JPanel

    hello to all,
    i'm realizing an application with Swing.
    i have realized a class that extends JPanel(called "PanelLayer") and, other to draw a ruler as Office 2003, it must contain an other subclass of JPanel (called "PanelLayer") that, in turn, will contain a JEditorPane.
    the problem is strange: i should continue in moviment the mouse to look well the JEditorPane (or subclasses)
    the URL is a image of the result that i get...
    URL : http://phantom89.helloweb.eu/img/img.jpg
    codes:
    public class Layer extends JPanel implements ComponentListener{
        private static final long serialVersionUID = 1L;
        private Rectangle2D.Double areaCentrale = new Rectangle2D.Double(100,100,850,1285);
        private double larghFoglio = 21.0*50;
        private double altFoglio = 29.7*50;
        private double zoom = 1.0;
        private JScrollPane sp = new JScrollPane(this);
        private Rectangle2D.Double posFoglio = new Rectangle2D.Double();
        private int lastX,lastY;
        private PanelLayer pl;
        private Point mouse = null;
        private JEditorPane text;
        public Layer(PanelLayer pl){
            this.setLayout(null);
            this.pl = pl;
            this.setPreferredSize(new Dimension((int)(40+larghFoglio*zoom), (int)(100+altFoglio*zoom)));
            areaCentrale = new Rectangle2D.Double(100*zoom,100*zoom,850*zoom,1285*zoom);
                sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            //try{
                text = new JEditorPane();
                text.setBounds(50,50,200,200);
                this.add(text);
            //}catch(IOException e){}
            lastX = sp.getHorizontalScrollBar().getValue();
            lastY = sp.getVerticalScrollBar().getValue();
            this.addComponentListener(this);
            this.addMouseListener(this);
            this.addMouseMotionListener(this);
        public void paintComponent(Graphics g){
            if(posFoglio.height + posFoglio.width == 0){
                this.posFoglio = new Rectangle2D.Double((this.getWidth()-larghFoglio*zoom)/2,50,larghFoglio*zoom,altFoglio*zoom);       
            Graphics2D g2d = (Graphics2D)g;
            g2d.setPaint(Color.lightGray);
            g2d.fillRect(0,0,this.getWidth(),this.getHeight());
            g2d.translate((this.getWidth()-larghFoglio*zoom)/2,50);
            g2d.setPaint(Color.black);
            g2d.draw(new Rectangle2D.Double(0,0,larghFoglio*zoom,altFoglio*zoom));
            g2d.setPaint(Color.white);
            g2d.fill(new Rectangle2D.Double(1,1,larghFoglio*zoom-1,altFoglio*zoom-1));
            g2d.setPaint(Color.blue);
            g2d.draw(areaCentrale);
        public JScrollPane getJScrollPane(){
            return sp;
        public Rectangle2D.Double getDimFoglio(){       
            return this.posFoglio;
        public double getCmWidth(){
            return larghFoglio*zoom/50+((larghFoglio*zoom/50)%1 <= getIncr() ? 0 : getIncr());
        public double getCmHeight(){
            return altFoglio*zoom/50+((altFoglio*zoom/50)%1 <= getIncr() ? 0 : getIncr());
        public Point getPointMouse(){
            return mouse;
        public void refresh(){
            lastX = sp.getHorizontalScrollBar().getValue();
            posFoglio.x = (this.getWidth()-larghFoglio*zoom)/2-lastX;
        public double getIncr(){
            return zoom/2;
        public void mouseClicked(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {
            mouse = e.getPoint();
            mouse.x -= sp.getHorizontalScrollBar().getValue();
            mouse.y -= sp.getVerticalScrollBar().getValue();
            pl.repaint();
        public void componentHidden(ComponentEvent e) {}
        public void componentMoved(ComponentEvent e) {
            lastX = sp.getHorizontalScrollBar().getValue();
            posFoglio.x = (this.getWidth()-larghFoglio*zoom)/2-lastX;
            lastY = sp.getVerticalScrollBar().getValue();
            posFoglio.y = 50-lastY;
            pl.repaint();
        public void componentResized(ComponentEvent e) {
            this.repaint();
            pl.repaint();
        public void componentShown(ComponentEvent e) {}
    public class PanelLayer extends JPanel implements MouseWheelListener,MouseInputListener{
        private static final long serialVersionUID = 1L;
        private Layer layer;
        private JScrollPane sp = null;
        private boolean visualizzaMouse = false;
        public PanelLayer(){
            this.setLayout(null);
            layer = new Layer(this);
            layer.addMouseListener(this);
            layer.addMouseMotionListener(this);
        public void paintComponent(Graphics g){
            if(layer.getDimFoglio().getWidth()+layer.getDimFoglio().getHeight() == 0){
                layer.setSize(50,50);
            if(sp == null){
                sp = layer.getJScrollPane();
                sp.addMouseWheelListener(this);
                sp.setBounds(30,30,this.getWidth()-30,this.getHeight()-30);
                this.add(sp);
            }else{
                layer.refresh();
            sp.setBounds(30,30,this.getWidth()-30,this.getHeight()-30);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setPaint(new Color(153,255,153));
            g2d.fill(new Rectangle2D.Double(0,0,this.getWidth(),30));
            g2d.fill(new Rectangle2D.Double(0,0,30,this.getHeight()));
            g2d.setPaint(Color.black);
            g2d.drawLine(0,0,this.getWidth(),0);
            g2d.drawLine(0,30,this.getWidth(),30);
            g2d.drawLine(0,0,0,this.getHeight());
            g2d.drawLine(30,0,30,this.getHeight());
            for(double i=0,j=0;i<=layer.getCmWidth();i+=layer.getIncr(),j++){
                if(j%2==0){
                    g2d.drawLine((int)(layer.getDimFoglio().x+31+i*50), 15,(int)(layer.getDimFoglio().x+31+i*50), 30);
                    g2d.drawString(String.valueOf((int)(j/2)), (float)(layer.getDimFoglio().x+31+i*50), 13);               
                }else{
                    g2d.drawLine((int)(layer.getDimFoglio().x+31+i*50), 22,(int)(layer.getDimFoglio().x+31+i*50), 30);
            for(double i=0,j=0;i<=layer.getCmHeight();i+=layer.getIncr(),j++){
                if(j%2==0){
                    g2d.drawLine(15, (int)(layer.getDimFoglio().y+31+i*50),30,(int)(layer.getDimFoglio().y+31+i*50));
                    g2d.drawString(String.valueOf((int)(j/2)),5,(float)(layer.getDimFoglio().y+31+i*50));
                }else{
                    g2d.drawLine(22, (int)(layer.getDimFoglio().y+31+i*50),30,(int)(layer.getDimFoglio().y+31+i*50));
            if((layer.getPointMouse() != null)&&(visualizzaMouse)){
                g2d.drawLine(layer.getPointMouse().x+30,0,layer.getPointMouse().x+30,30);
                g2d.drawLine(0,layer.getPointMouse().y+30,30,layer.getPointMouse().y+30);
            g2d.setPaint(new Color(153,255,153));
            g2d.fillRect(1,1,29,29);
            int largh = layer.getJScrollPane().getVerticalScrollBar().getWidth();
            g2d.fillRect(this.getWidth()-largh, 1, largh, 29);
            g2d.fillRect(1, this.getHeight()-largh, 29, largh);
        public void mouseWheelMoved(MouseWheelEvent e) {
            JScrollBar vsb = layer.getJScrollPane().getVerticalScrollBar();
            vsb.setValue(vsb.getValue()+20*e.getWheelRotation());
        public void refresh(){
            if((layer != null)&&(sp != null)){
                layer.setSize(this.getWidth()-30,this.getHeight()-30);
                sp.setViewportView(layer);
                this.repaint();
        public void mouseClicked(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {
            visualizzaMouse = true;
            repaint();
        public void mouseExited(MouseEvent e) {
            visualizzaMouse = false;
            repaint();
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {}
    }(my english isn't very good)

    Don't really understand what the posted code does and I can't execute the code so I don't have much to offer.
    But I did notice that you don't invoke super.paintComponent(...) which means you may have garbage being painted on the panels.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html

  • Closing a class that extends JPanel

    Hi, i have a class that extends JPanel(lets call it class A). In that class, if the user click the logout button, i want class A to close and display class B that extends JFrame. right now, i am able to call class B, but i cannot close class A.
    I uses remove() to close class A, but it doesnt work... could u tell me what to do??
    I put this code in class A...
    if (e.getSource() == logoutButton)     {
         remove(this);
         new Rest_Login1();
         String [] ar = null;
         Rest_Login1.main(ar);
    } Thx

    so i want to remove the CustomerPanel3 and display the Rest_Login1...
    some of my code look like this.
    thx
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class CustomerPanel3 extends JPanel implements ActionListener
    // some JButton, JLabel n etc
         public void actionPerformed (ActionEvent e)
              if (e.getSource() == logoutButton)     {
                   remove(this);
                   new Rest_Login1();
                   String [] ar = null;
                   Rest_Login1.main(ar);
    public class Rest_Login1 {
         public static void main(String args[])
              JFrame login1 = new JFrame("Login User Interface");
              JFrame.setDefaultLookAndFeelDecorated(true);
              RestaurantLogin userpan = new RestaurantLogin();
              login1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              login1.setSize(600, 250);
              login1.setLocation(230,192);
              login1.getContentPane().add(userpan);
              login1.setVisible(true);
    }

  • Transform a class that implements JPanel into a bean.

    I'd to create a bean, from a class that implements JPanel, that in fact is a custom component.
    How can I create a bean?
    I have absolutely no idea about beans.
    What can make beans for me?
    I know a lot about the theory of ejb, is this what I need?
    I'm quite confused, please make me see the light!!!!!
    Thanks.

    Hi Daniel!
    To answer your question short as possible:
    Java -Beans are reusable code - components,
    similar to VB Active -X components,
    which you can use when developing your own
    applications.
    Beans can have a graphic user interface, so you
    can use builder tools like JBuilder or Beanbox
    to show them graphically in a designer.
    You can modify them about their properties,
    mostly shown in a special property window of a
    builder tool.
    It's really not very hard to create your own beans,
    the only thing you have to do is to pack all the
    classes which make the bean into a jar file.
    Then you can import the bean with the builder
    and it will be shown.
    The jar manifest file needs to look like for example:
    Manifest-Version: 1.0
    Name: BeanClock.class
    Java-Bean: True
    All the properties are implemented by public property-get
    and property-set methods, in order to show them in the property window.
    Java is doing that by introspection.
    Hope, this makes it a little bit clearer for you!

  • Can I create the object of an protected inner class of a Base class in to t

    Dear All,
    Can I create the object of an protected inner class of a Base class in to the subclass ?
    e.g.
    public class Base{
         protected class Inner {};
    Public class Sub extends Base{
         Public Inner amethod (){
              Return new Inner(); //here I get an exception as
                                //Inner has protected access
    }Regards,
    Ishan

    @Op. The code that you posted isn't close to compiling. Java is case sensitive. It should be public and not Public, and return instead of Return.
    Kaj

  • Can I use the inner class of one containing class by the other class

    Can I use the inner class of one containing class by the other class in the same package as the containing class
    eg I have a class BST which has inner class Enumerator. Can I use the inner class from the other class in the same pacckage as BST?

    Inner classes do not share the namespace of the package of the containing class. Also they are never visible to other classes in the same package.Believe what you want, then, if you're going to make up your own rules about how Java works. For people interested in how Java actually works, here is an example that shows why that assertion is false:
    package com.yawmark.jdc;
    public class Outer {
         public class Inner {
    }And...
    package com.yawmark.demo;
    import com.yawmark.jdc.*;
    public class Demo {
         public static void main(String[] args) {
              assert new Outer().new Inner() != null;
    }~

  • Referencing WMI Manageable class from another WMI Class

    Hi,
    I am trying to have WMI manageable class referring to another WMI manageable class
    Something like
    [ManagementEntity]
    Class A
    [ManagementEntity]
    Class B
            [ManagementReference(Type = "A")]
            [ManagementProbe]
            public A AClass;
    When trying to install the class, I am getting “Type unsupported”
    I tried the Microsoft
    ManagementReference sample,
    http://msdn.microsoft.com/en-us/library/system.management.instrumentation.managementreferenceattribute.aspx
    (working fine but the LetterPhonetic class won’t show on the WMI Object Browser)
    Ideas will be highly appreciated
    My Sample code
    using System;
    using System.Management.Instrumentation;
    using System.Collections.Concurrent;
    using System.Collections;
    [assembly: WmiConfiguration("root\\ConsoleC", HostingModel = ManagementHostingModel.Decoupled)]
    namespace ConsoleDecoupled
        [System.ComponentModel.RunInstaller(true)]
        public class TheInstaller : DefaultManagementInstaller
        public class Program
            public static void Main(string[] args)
                for (int i = 0; i < 10; ++i)
                    TestEnumWmi ms = TestEnumWmi.CreateTestEnumWmi();
                    ms.teststring = i.ToString();
                InstrumentationManager.RegisterType(typeof(TestEnumWmi));
                InstrumentationManager.RegisterType(typeof(RuntimeConfigSettings));
                Console.WriteLine("Press enter to exit");
                Console.ReadLine();
                InstrumentationManager.UnregisterType(typeof(TestEnumWmi));
                InstrumentationManager.UnregisterType(typeof(RuntimeConfigSettings));
        [ManagementEntity(Singleton = true, Name = "ConfigurationSample")]
        [ManagementQualifier("Description", Value = "Configuration Sample Application")]
        public class RuntimeConfigSettings
            [ManagementProbe]
            public string[] ReadMe;
            private int myVar;
            [ManagementConfiguration]
            public int MyProperty
                get { return myVar; }
                set { myVar = value; Console.WriteLine(value); }
            [ManagementReference(Type = "TestEnumWmi")]
            [ManagementProbe]
            public TestEnumWmi MSS;
            [ManagementBind]
            public RuntimeConfigSettings()
                ReadMe = new string[10];
                for (int i = 0; i < 10; ++i)
                    ReadMe[i] = "blah " + i;
        [ManagementEntity(Name = "TestEnumWmi")]
        public class TestEnumWmi
            private TestEnumWmi()
            static internal TestEnumWmi CreateTestEnumWmi()
                TestEnumWmi ms = new TestEnumWmi();
                ms._id = Guid.NewGuid().ToString();
                ms.teststring = "blah";
                ms.TestInt = new Random().NextDouble();
                instantlist.TryAdd(ms._id, ms);
                return ms;
            [ManagementConfiguration()]
            public double TestInt { get; set; }
            [ManagementConfiguration()]
            public string teststring { get; set; }
            [ManagementKey(Name = "ID")]
            public string _id;
            [ManagementBind]
            static public TestEnumWmi GetInstant([ManagementName("ID")] string ID)
                TestEnumWmi ms = null;
                if (instantlist.TryGetValue(ID, out ms))
                    return ms;
                else
                    throw new InstanceNotFoundException();
            [ManagementEnumerator]
            static public IEnumerable EnumerateTestEnumWmis()
                foreach (var i in instantlist)
                    yield return i.Value;
            static internal ConcurrentDictionary<string, TestEnumWmi> instantlist = new ConcurrentDictionary<string, TestEnumWmi>();

    Hi,
    The Microsoft ManagementReference sample you mentioned contains a bug:
    Instead of:
    inst.LetterNumber = "Letter = " + i;
    inst.PhoneticNumber = "Phonetic = " + i;
    The exact text (where spaces in the string are important and must be removed) should be:
    inst.LetterNumber = "NumberLetter.Number=" + i;
    inst.PhoneticNumber = "NumberPhonetic.Number=" + i;
    With this fix, the hierarchy can now be navigated properly.
    c.f. my response to the following blog post:
    http://juggledthoughts.blogspot.co.uk/2008/06/wmi-association-classes.html
    I have also
    logged a bug on MSDN Feedback so please vote on this if you'd like them to fix the sample.

  • How to access class variables in anonymous class??.

    I have a boolean class level variable. Fom a button action , this boolean will set to true and then it used in anonymous class. In anonymous class, I am getting default value instead of true. Could u anyone help in this plzzz.

    first of all, you don't want parent because that is something that Containers use to remember their containment hierarchy. you are thinking of super which is also incorrect, because that has to do with inheritance.
    the problem here is a scoping problem. you generally would use final if you were accessing variables in an anonymous class that are in the local scope. in this case, you just need to create some test code and play with it. snip the code below and play with it. it shows both the given examples and some additional ways to change/display class variables.
    good luck, hackerx
    import javax.swing.*;
    import java.awt.event.*;
    public class Foo extends JPanel
         private boolean the_b = true;
         public static void main(String[] args)
              Foo f = new Foo();
              JFrame frame = new JFrame();
              frame.getContentPane().add(f);
              frame.pack();
              frame.show();
         public Foo()
              // get your button
              JButton b = new JButton("Not!");
              b.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        // *** uncomment these to play around ***
                        // Foo.this.the_b = false; // this will work, but unnecessary
                        // the_b = false; // this works fine too
                        notFoo();
              this.add(b);
              // something to show the value that accesses a class variable
              // using an inner class instead of final nonsense
              DisplayThread t = new DisplayThread();
              t.start();
         private void notFoo()
              the_b = !the_b;
         class DisplayThread extends Thread
              public void run()
                   while(true)
                        System.err.println("boolean value: " + the_b);
                        try {
                        sleep(1000);
                        } catch(InterruptedException ie) {}
    }

  • Calling a class method from another class

    how can i call a method / function of one class without extending that class in another class.
    and one thing more i want want o check wether any Swing gui is open or closed.

    how can i call a method / function of one class without extending that class in another class.What?... Umm... You just call it... as in Foo.bar("doe ray me");
    i want want to check if any Swing gui is open or closed.Ummm, what? I don't understand the question. Do you mean find out if a particular java programming is allready running, of do you mean is the JPanel visible, or something else?

  • Using variables in 5 instances of one Class in a seperate Class

    I have 5 instances of the one Class all returning different values. These values are parameteres for a final calculation. I am using Sliders as my data validation and I want my final calculation to react to the individual sliders being moved. I need to know the name of the slider and its value or do I?
    I would like to Calculate Tractive effort in Extra Panel, I know that all this has something to do with Event Handling but what?
    Any and help vastly appreciated otherwise I am goint to eat this computer cables and all.
    By the way I Hate Computers!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    Code as follows:
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class TractiveEffortCalculator extends JFrame
         private static final long serialVersionUID = 1L;
         public ConstructParametersPanel Instance = new ConstructParametersPanel();
         public ExtraPanel Sample = new ExtraPanel();
         public JPanel thisPanel;
         public TractiveEffortCalculator()
              thisPanel = new JPanel();
              //super ("N Generation Steam"+"           "+"Tractive Effort Calculator");
              BackGroundColour myColor = new BackGroundColour();
              //ConstructParametersPanel Instance = new ConstructParametersPanel();
              GridLayout grid = new GridLayout();
              grid.setColumns(2);
              grid.setHgap(10);
              grid.setRows(1);
              grid.setVgap(5);
              thisPanel.setLayout(grid);
              thisPanel.add(Instance.ConstructParametersPanelMethod());
              thisPanel.add(Sample.ExtraPanelMethod());
              setBackground(myColor.NewBackGroundColour());
              getContentPane().add(thisPanel);
              pack();
              setVisible(true);
              setLocation(40,50);
              setSize(800,600);
              //setResizable(false);
         public static void main(final String[]args)
              final TractiveEffortCalculator app = new TractiveEffortCalculator();
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JPanel;
    public class ConstructParametersPanel extends JPanel
         private static final long serialVersionUID = 1L;
         private JPanel sidePanel;
         TheSliderClass Instance1 = new TheSliderClass();
         TheSliderClass Instance2 = new TheSliderClass();
         TheSliderClass Instance3 = new TheSliderClass();
         TheSliderClass Instance4 = new TheSliderClass();
         TheSliderClass Instance5 = new TheSliderClass();
         public JPanel ConstructParametersPanelMethod()
              sidePanel = new JPanel();
              BackGroundColour myColor = new BackGroundColour();
              GreenColour myColor2 = new GreenColour();
              BlackShadowColour myColor3 = new BlackShadowColour();
              sidePanel.setBorder(BorderFactory.createBevelBorder(1
                                                                          ,myColor2.NewGreenColour()
                                                                          ,myColor3.NewBlackShadowColour()
                                                                          ,myColor2.NewGreenColour()
                                                                          ,myColor3.NewBlackShadowColour()));
              GridLayout grid = new GridLayout();
              grid.setColumns(1);
              grid.setHgap(10);
              grid.setRows(6);
              grid.setVgap(5);
              sidePanel.setLayout(grid);
              sidePanel.setBackground(myColor.NewBackGroundColour());
              sidePanel.add(Instance1.TheSliderClassMethod("Boiler Pressure",200,320));
              sidePanel.add(Instance2.TheSliderClassMethod("Wheel Diameter",60,80));
              sidePanel.add(Instance3.TheSliderClassMethod("Stroke",10,20));
              sidePanel.add(Instance4.TheSliderClassMethod("Piston Rod",2,4));
              sidePanel.add(Instance5.TheSliderClassMethod("Tail Rod",1,3));
              return sidePanel;          
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JFormattedTextField;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSlider;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.text.NumberFormatter;
    public class TheSliderClass extends JPanel implements ChangeListener
         private static final long serialVersionUID = 1L;
         //Add a formatted text field to supplement the slider.
         public JFormattedTextField textField,textField2;
         public String publicSliderName = "";
         public int fps;
         //And here's the slider.
         public JSlider sliderParameterValue;
         JPanel labelAndTextField,allTogether;
         int TractiveEffort = 0;
         public JPanel TheSliderClassMethod(String sliderName, int minimumValue, int maximumValue)
              JPanel allTogether = new JPanel();
              Font font = new Font("palatino linotype regular", Font.BOLD, 12);
              int initialValue = ((minimumValue+maximumValue)/2);
              int tickMarkValue = (maximumValue-minimumValue);
              publicSliderName = sliderName;
              //Create the label.
              JLabel sliderLabel = new JLabel(sliderName,JLabel.CENTER);
              sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
              sliderLabel.setFont(font);
              sliderLabel.setForeground(Color.BLUE);
              //Create the formatted text field and its formatter.
              java.text.NumberFormat numberFormat =
                   java.text.NumberFormat.getIntegerInstance();
              NumberFormatter formatter = new NumberFormatter(numberFormat);
              formatter.setMinimum(new Integer(minimumValue));
              formatter.setMaximum(new Integer(maximumValue));
              textField = new JFormattedTextField(formatter);
              textField.setValue(new Integer(initialValue));
              textField.setColumns(3); //get some space
              textField.setEditable(false);
              textField.setForeground(Color.red);
              textField2 = new JFormattedTextField(formatter);
              textField2.setValue(new Integer(initialValue));
              textField2.setColumns(3); //get some space
              textField2.setEditable(false);
              textField2.setForeground(Color.red);
              //Create the slider.
              sliderParameterValue = new JSlider(JSlider.HORIZONTAL,
              minimumValue, maximumValue, initialValue);
              sliderParameterValue.addChangeListener(this);
              //Turn on labels at major tick marks.
              sliderParameterValue.setMajorTickSpacing(tickMarkValue);
              sliderParameterValue.setMinorTickSpacing(10);
              sliderParameterValue.setPaintTicks(true);
              sliderParameterValue.setPaintLabels(true);
              sliderParameterValue.setBorder(
              BorderFactory.createEmptyBorder(0,0,0,0));
                                                      sliderParameterValue.setBackground(Color.cyan);
              //Create a subpanel for the label and text field.
              JPanel labelAndTextField = new JPanel(); //use FlowLayout
              labelAndTextField.setBackground(Color.cyan);      
              labelAndTextField.add(sliderLabel);
              labelAndTextField.add(textField);
              //Put everything together.
              GridLayout gridThis = new GridLayout();
              gridThis.setColumns(1);
              gridThis.setRows(2);
              allTogether.setLayout(gridThis);
              allTogether.add(labelAndTextField);
              allTogether.add(sliderParameterValue);
              allTogether.setBorder(BorderFactory.createBevelBorder(1,Color.red,
                                                                                    Color.red));
              return allTogether;
         /** Listen to the slider. */
         public void stateChanged(ChangeEvent e)
              JSlider source = (JSlider)e.getSource();
              fps = (int)source.getValue();
              textField.setText(String.valueOf(fps));
              textField2.setText(String.valueOf(fps));
    import java.awt.GridLayout;
    import javax.swing.JPanel;
    public class ExtraPanel extends JPanel
         private static final long serialVersionUID = 1L;
         public JPanel thisPanel;
         public ConstructParametersPanel aPointer;
         public JPanel ExtraPanelMethod()
              thisPanel = new JPanel();
              aPointer = new ConstructParametersPanel();
              GridLayout grid = new GridLayout();
              grid.setColumns(1);
              grid.setHgap(10);
              grid.setRows(6);
              grid.setVgap(5);
              thisPanel.setLayout(grid);
              return thisPanel;

    I don't know if anyone's going to go through all that code...but here's a hint.
    if you have 5 sliders and each one represents a separate variable you're going to use in your calculation...you will need to be able to read the change in THAT PARTICULAR slider to update that particular variable and recalculate.
    So you have a change state listener: The ChangeEvent passed to the
    public void stateChanged(ChangeEvent e) method will have a method called getSource() which you use. However, you aren't figuring out which slider it came from, you're just updating the text areas with info that comes from ANY slider.
    You can use e.getSource() to identify which slider it came from.
    Say you had the following JSlider sl1, sl2, sl3, sl4.
    And each one represents int int1, int2, int3, int4;
    what you do in your stateChanged code say
    if (e.getSource()==sl1){
    int1 = sl1.getValue();
    } else if (e.getSource()==sl2){
      int2 = sl2.getValue();
    } now you have identified which slider was activated. Hope this helps!

  • Problem in generic value copier class / reflection and generic classes

    Hello experts,
    I try to archive the following and am struggling for quite some time now. Can someone please give an assessment if this is possible:
    I am trying to write a generic data copy method. It searches for all (parameterless) getter methods in the source object that have a corresponding setter method (with same name but prefixed by "set" instead of "get" and with exactly one parameter) in the destination object.
    For each pair I found I do the following: If the param of the setter type (T2) is assignable from the return type of the getter (T1), I just assign the value. If the types are not compatible, I want to instantiate a new instance of T2, assign it via the setter, and invoke copyData recursively on the object I get from the getter (as source) and the newly created instance (as destination). The assumption is here, that the occurring source and destination objects are incompatible but have matching getter and setter names and at the leaves of the object tree, the types of the getters and setters are compatible so that the recursion ends.
    The core of the problem I am struggling with is the step where I instantiate the new destination object. If T2 is a non-generic type, this is straightforward. However, imagine T1 and T2 are parametrized collections: T1 is List<T3> and T2 is List<T4>. Then I need special handling of the collection. I can easily iterate over the elements of the source List and get the types of the elements, but I can not instantiate only a generic version of the destinatino List. Further I cannot create elements of T4 and add it to the list of T2 and go into recursion, since the information that the inner type of the destination list is T4 is not available at run-time.
    public class Source {
       T1 getA();
       setA(T1 x);
    public class Dest {
       T2 getA();
       setA(T2 x);
    public class BeanDataCopier {
       public static void copyData(Object source, Object destination) {
          for (Method getterMethod : sourceGetterMethods) {
             ... // find matching getter and setter names
             Class sourceParamT = [class of return value of the getter];
             Class destParamT = [class of single param of the setter];
             // special handling for collections -  I could use some help here
             // if types are not compatible
             Object destParam = destination.getClass().newInstance();
             Object sourceParam = source.[invoke getter method];
             copyData(sourceParam, destParam);
    // usage of the method
    Souce s = new Source(); // this is an example, I do not know the type of s at copying time
    Dest d = new Dest(); // the same is true for d
    // initialize s in a complicated way (actually JAX-B does this)
    // copy values of s to d
    BeanDataCopier.copyData(s, d);
    // now d should have copied values from s Can you provide me with any alternative approaches to implement this "duck typing" behaviour on copying properties?
    Best regards,
    Patrik
    PS: You might have guessed my overall use case: I am sending an object tree over a web service. On the server side, the web service operation has a deeply nested object structure as the return type. On the client side, these resulting object tree has instances not of the original classes, but of client classes generated by axis. The original and generated classes are of different types but have the identically named getter and setter methods (which again have incompatible parameter types that however have consistent names). On the client side, I want to simply create an object of the original class and have the values of the client object (including the whole object tree) copied into it.
    Edited by: Patrik_Spiess on Sep 3, 2008 5:09 AM

    As I understand your use case this is already supported by Axis with beanMapping [http://ws.apache.org/axis/java/user-guide.html#EncodingYourBeansTheBeanSerializer]
    - Roy

Maybe you are looking for

  • Report using LOV's

    Hi all again, I am building a report and need to have the LOV display not the value in the table. I am useing Apex 4.1 on 11Gr2 with the build in html server. I have a table I am reporting on the has several fields that are values in several LOV tabl

  • Itunes 8.1 wont open

    I downloaded the new Itunes 8.1, but then when I try to open it, I get a message saying "Itunes Library .itl file is locked, on a locked disk, or you do not have write permission for this file. How can I fix this problem?

  • Blocking Ad servers via etc/host file not working

    In Snow Leopard I add a list of ad servers and direct them to 127.0.0.1 via the /ect/host file. I've configured the host file on my mac mini server and it doesn't work. i just want to block ads when using browsers ON the Mini. How can I achieve this?

  • Creating documents in arabic

    i am looking for a program to create an arabic newspaper. is indesign capable of arabic writing? does the program type properly? (right to left) does the program come standard with any arabic fonts? does the punctuation and other symbols display prop

  • Why have i lost purchased music from my itunes library

    itunes; why have i lost purchased music from my itunes library (files not found) and how do I get it back??