Problem with setContentPane() in JFrame class

I recently discovered a problem with the setContentPane method in the JFrame class. When I use setContentPane(Container ..), the previously existing contentPane remains in the stack. I have tried nullifying getContentPane(), and all manner of things, but, each time I use setContentPane, I have another instance of a JPanel in the stack.
I'm using code similar to setContentPane(new CustomJPanel()); and each time the user changes screens, and a similar call to that is made, the old CustomJPanel instance remains in the stack. Can anyone suggest a way around this? On their own the panels do not take up very much memory, but after several hours of usage, they will build up.

I tried what you suggested; it only resulted in a huge performance decrease. The problem with memory allocation is still there.
Here is the method I use to switch screens in my app:
public static void changeScreen (JPanel panel){
          try{
               appFrame.setTitle("Wordinary : \""+getTitle()+"\"");
               appFrame.setContentPane(panel);
               appFrame.setSize(appFrame.getContentPane().getPreferredSize());     
               appFrame.getContentPane().setBackground(backColour);
               for (int i = 0; i < appFrame.getContentPane().getComponents().length; i++)
                    appFrame.getContentPane().getComponents().setForeground(textColour);
               //System.out.println("Background colour set to "+backColour+" text colour set to "+textColour);
               appFrame.validate();
          catch (Exception e){
               //System.out.println("change");
               e.printStackTrace();
And it is called like this:
changeScreen(new AddWordPanel());The instantiation of the new instance is what is causing the memory problems, but I can't think of a way around it.

Similar Messages

  • Problem with running the midlet class (Error with Installation suite )

    hi everyone...
    i have problem with running the midlet class(BluetoothChatMIDlet.java)
    it keep showing me the same kind of error in the output pane of netbeans...
    which is:
    Installing suite from: http://127.0.0.1:49296/Chat.jad
    [WARN] [rms     ] javacall_file_open: wopen failed for: C:\Users\user\javame-sdk\3.0\work\0\appdb\delete_notify.dat
    i also did some research on this but due to lack of forum that discussing about this,im end up no where..
    from my research i also find out that some of the developer make a changes in class properties..
    where they check the SIGN DISTRIBUTION...and also change the ALIAS to UNTRUSTED..after that,click the EXPORT KEY INTO JAVA ME SDK,PLATFORM,EMULATOR...
    i did that but also didnt work out..
    could any1 teach me how to fix it...
    thanx in advance... :)

    actually, i do my FYP on bluetooth chatting...
    and there will be more than two emulators running at the same time..
    one of my frens said that if u want to run more than one emulator u just simply click on run button..
    and it will appear on the screen..

  • Weird problem with jpanel vs jframe

    I'm using jmathplot.jar from JMathTools which lets me do 3d plotting. I used a JFrame to get some code to work and it worked fine. Here's the code that worked for a JFrame:
    public class View extends JFrame
        private Model myModel;
        private Plot3DPanel myPanel;
        // ... Components
        public View(Model m)
            myModel = m; 
            // ... Initialize components
            myPanel = new Plot3DPanel("SOUTH");
            myPanel.addGridPlot("Test",myModel.getXRange(),myModel.getYRange(),myModel.getZValues());
            setSize(600, 600);
            setContentPane(myPanel);
            setVisible(true);
    }Here's the class that starts everything:
    public class TestApplet extends JApplet
        public void init()
            //Execute a job on the event-dispatching thread; creating this applet's GUI.
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        createGUI();
            catch (Exception e)
                e.printStackTrace();
        private void createGUI()
            System.out.println("Creating GUI");
            Model model = new Model();
            View view = new View(model);
    }And here's the Model:
    public class Model
        private double[] myXRange,myYRange;
        private double[][] myZValues;
        public Model()
            createDataSet();
        public double[] getXRange()
            return myXRange;
        public double[] getYRange()
            return myYRange;
        public double[][] getZValues()
            return myZValues;
        private void createDataSet()
            myXRange = new double[10];
            myYRange = new double[10];
            myZValues = new double[10][10];
            for(double i=0;i<10;i++)
                for(double j=0;j<10;j++)
                    double x = i/10;
                    double y = j/10;
                    myXRange[(int) i] = x;
                    myYRange[(int) j] = y;
                    myZValues[(int) i][(int) j]= Math.cos(x*Math.PI)*Math.sin(y*Math.PI);
    }However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and changed:
    setSize(600, 600);
    setContentPane(myPanel);
    setVisible(true);to
    this.add(myPanel);and added these two lines to createGUI():
            view.setOpaque(true);
            setContentPane(view);When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet. I don't know if it's a problem with the library or if I'm doing something wrong in my applet.

    However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and (...)What do you mean? View extends JApplet? I thought View was meant to extend JPanel in the end...
    When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet.Or, the panel has its preferred size, and this latter is too small. Actually the panel has the size its container's layout manager awards it (taking or not the panel's preferred, minimum, and maximum sizes into account). See the tutorial on [layout managers|http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html] .
    In particular, this line adds the myPanel to a parent panel (presumably, it is in class View which extends JPanel, whose default layout is FlowLayout):
    this.add(myPanel);
    I don't know if it's a problem with the library or if I'm doing something wrong in my applet.Likely not (presumably the library interfers only in how it computes the Plot3DPanel's preferred size). There's an easy way to tell: try to layout correctly a custom JPanel of yours, containing only e.g. a button with an icon. Once you understand the basics of layout management, revisit the example using ther 3rd-party library.
    N.B.: there are a lot of "likely" and "presumably" in my reply: in order to avoid hardly-educated guesses especially on what is or isn't in your actual code, you'd better provide an SSCCE , which means reproducing the problem without the 3rd party library.

  • Problem with ScrollPane and JFrame Size

    Hi,
    The code is workin but after change the size of frame it works CORRECTLY.Please help me why this frame is small an scrollpane doesn't show at the beginning.
    Here is the code:
    import java.awt.*;
    public class canvasExp extends Canvas
         private static final long serialVersionUID = 1L;
         ImageLoader map=new ImageLoader();
        Image img = map.GetImg();
        int h, w;               // the height and width of this canvas
         public void update(Graphics g)
            paint(g);
        public void paint(Graphics g)
                if(img != null)
                     h = getSize().height;
                     System.out.println("h:"+h);
                      w = getSize().width;
                      System.out.println("w:"+w);
                      g.drawRect(0,0, w-1, h-1);     // Draw border
                  //  System.out.println("Size= "+this.getSize());
                     g.drawImage(img, 0,0,this.getWidth(),this.getHeight(), this);
                    int width = img.getWidth(this);
                    //System.out.println("W: "+width);
                    int height = img.getHeight(this);
                    //System.out.println("H: "+height);
                    if(width != -1 && width != getWidth())
                        setSize(width, getHeight());
                    if(height != -1 && height != getHeight())
                        setSize(getWidth(), height);
    }I create frame here...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class frame extends JFrame implements MouseMotionListener,MouseListener
         private static final long serialVersionUID = 1L;
        private ScrollPane scrollPane;
        private int dragStartX;
        private int dragStartY;
        private int lastX;
        private int lastY;
        int cordX;
        int cordY;
        canvasExp canvas;
        public frame()
            super("test");
            canvas = new canvasExp();
            canvas.addMouseListener(this);
            canvas.addMouseMotionListener(this);
            scrollPane = new ScrollPane();
            scrollPane.setEnabled(true);
            scrollPane.add(canvas);
            add(scrollPane);
            setSize(300,300);
            pack();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void mousePressed(MouseEvent e)
            dragStartX = e.getX();
            dragStartY = e.getY();
            lastX = getX();
            lastY = getY();
        public void mouseReleased(MouseEvent mouseevent)
        public void mouseClicked(MouseEvent e)
            cordX = e.getX();
            cordY = e.getY();
            System.out.println((new StringBuilder()).append(cordX).append(",").append(cordY).toString());
        public void mouseEntered(MouseEvent mouseevent)
        public void mouseExited(MouseEvent mouseevent)
        public void mouseMoved(MouseEvent mouseevent)
        public void mouseDragged(MouseEvent e)
            if(e.getX() != lastX || e.getY() != lastY)
                Point p = scrollPane.getScrollPosition();
                p.translate(dragStartX - e.getX(), dragStartY - e.getY());
                scrollPane.setScrollPosition(p);
    }...and call here
    public class main {
         public main(){}
         public static void main (String args[])
             frame f = new frame();
    }There is something I couldn't see here.By the way ImageLoader is workin I get the image.
    Thank you for your help,please answer me....

    I'm not going to even attempt to resolve the problem posted. There are other problems with your code that should take priority.
    -- class names by convention start with a capital letter.
    -- don't use the name of a common class from the standard API for your custom class, not even with a difference of case. It'll come back to bite you.
    -- don't mix awt and Swing components in the same GUI. Change your class that extends Canvas to extend JPanel instead, and override paintComponent(...) instead of paint(...).
    -- launch your GUI on the EDT by wrapping it in a SwingUtilities.invokeLater or EventQueue.invokeLater.
    -- calling setSize(...) followed by pack() is meaningless. Use one or the other.
    -- That's not the correct way to display a component in a scroll pane.
    Ah, well, and the problem is that when you call pack(), it retrieves the preferredSize of the components in the JFrame, and you haven't set a preferredSize for the scroll pane.
    Please, for your own good, take a break from whatever it is you're working on and go through The Java&#8482; Tutorials: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]
    db

  • Problem with JPanel in JFrame

    hai ashrivastava..
    thank u for sending this one..now i got some more problems with that screen .. actually i am added one JPanel to JFrame with BorderLayout at south..the problem is when i am drawing diagram..the part of diagram bellow JPanel is now not visible...and one more problem is ,after adding 6 ro 7 buttons remaing buttons are not vissible..how to increase the size of that JPanel...to add that JPanel i used bellow code
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    f.getContentPane().add(BorderLayout.SOUTH, panel);

    Hi
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    // Add this line to ur code with ur requiredWidth and requiredHeight
    panel.setPreferredSize(new Dimension(requiredWidth,requiredHeight));
    f.getContentPane().add(BorderLayout.SOUTH, panel);
    This should solve ur problem
    Ashish

  • Problem with Dynamically accessing EJB Class objects in WL 7.0 SP1

    I am trying to build a component which has the ability to instantiate and execute
    an known EJB method on the fly.
    I have managed to build the component but when I try and execute it I get a ClassNotFoundException.
    I know that the EJB I am trying to invoke is deployed and available on the server,
    as I can see it in the console, I also seen to have been able to get the remote
    interface of the object, my problem occurs when I try and access the class object
    so I can perform a create on the object and then execute my method
    The code I have written is below:
    private Object getRemoteObject(Context pCtx, String pJNDIName, String pHomeBean)
    throws Exception {
         String homeCreate = "create";
         Class []homeCreateParam = { };
         Object []homeCreateParamValues = {};           
    try {  
    //This call seems to work and doesn't throw an exception     
    Object home = pCtx.lookup(pJNDIName);
    //However this call throws a java.lang.ClassNotFoundException
    Class homeBean = Class.forName(pHomeBean);
    Method homeCreateMethod = homeBean.getMethod(homeCreate,homeCreateParam);
    return homeCreateMethod.invoke(home, homeCreateParamValues);
    } catch (NamingException ne) {             
    logStandardErrorMessage("The client was unable to lookup the EJBHome.
    Please make sure ");
    logStandardErrorMessage("that you have deployed the ejb with the JNDI
    name "+pJNDIName+" on the WebLogic server ");
    throw ne;
    } catch (Exception e) {
    logStandardErrorMessage(e.toString());
    throw e;     
    Any advice would be really appreciated, I'm fast running out of ideas, I suspect
    it has something to do with the class loader but I'm not sure how to resolve it
    Regards
    Jo Corless

    Hello Joanne,
    Congratulations! I'm very happy that you've managed to fix your problem. It's
    always essential to understand how to package applications when deploying on BEA
    WebLogic. Usually, by throwing everything into an EAR file solves just about all
    the class loader problems. :-) Let us know if you have any further problems that
    we can assist you with.
    Best regards,
    Ryan LeCompte
    [email protected]
    http://www.louisiana.edu/~rml7669
    "Joanne Corless" <[email protected]> wrote:
    >
    >
    I've fixed it!!!!!!!!
    Thanks to everyone who gave me help!!!!
    The class loader was the culprit which is what I suspected all along.
    As soon
    as I put the 2 jar files I was using into an EAR file the problem went
    away!!!!!
    Thanks again
    Jo Corless
    "Ryan LeCompte" <[email protected]> wrote:
    Hello Joanne,
    As Mr. Woollen mentioned, I also believe it's a problem with the class
    loader.
    You need to be careful how you arrange your EJBs, because WebLogic has
    a specific
    method in which it loads classes in an EAR, JAR, and WAR file(s). Please
    refer
    to http://dev2dev.bea.com/articles/musser.jsp for more information about
    BEA WebLogic
    class loading mechanisms and caveats. Also, try printing out the various
    methods
    that are available on the object that was returned to you via reflection.
    For
    example, use the getMethods() method, which returns an array of Method
    objects
    that you can subsequently cycle through and print out the various method
    names.
    This way you can discover if the class found/returned to you is indeed
    the one
    you intend to locate.
    Hope this helps,
    Ryan LeCompte
    [email protected]
    http://www.louisiana.edu/~rml7669
    Rob Woollen <[email protected]> wrote:
    I believe the issue is the home interface class for this EJB is not
    available in the class loader which is doing the reflection.
    If you do:
    getClass().getClassLoader().loadClass(homeInterfaceClassName)
    I suspect it will fail. Reflection still requires that the class be
    loadable.
    -- Rob
    Joanne Corless wrote:
    Hi Slava,
    If I make my code look like you describe below I get a compliationerror telling
    me that
    home.getMethod() is not recognised (no such method)
    If I change it slightly and use
    Method homeCreateMethod =
    home.getClass().getMethod(homeCreate,homeCreateParam);
    The code will compile OK but when executed it still throws a NoSuchMethodException
    Any ideas ?
    Thanks for your help so far
    Regards
    Jo Corless
    Your code should look like
    Object home = pCtx.lookup(pJNDIName);
    Method homeCreateMethod =
    home.getMethod(homeCreate,homeCreateParam);
    return homeCreateMethod.invoke(home, homeCreateParamValues);
    Regards,
    Slava Imeshev
    "Joanne Corless" <[email protected]> wrote in message
    news:[email protected]...
    Hi Ryan,
    I also wanted to mention that if you do a "header search" in this
    particular
    newsgroup
    with the search query as "reflection", you will see many previousmessages
    regarding
    reflection and EJBs. I believe you could learn a lot from thedifficulties
    that
    others have faced and solved.I tried that and although there was a number of similar cases noneof them
    actually
    seem to fix my issue. Thanks for the suggestion though
    Are the EJBs that you are trying to access accessible via your
    system
    classpath?
    Try to avoid having them accessible via the main system classpath,and
    only bundle
    them in your appropriate EJB jar files (contained in an EAR file,for
    example).Maybe I should have laid the problem out a little clearer.
    I have a number of EJB's bundled up in a JAR file which is hot deployedto
    the
    server. Within this first JAR file is an EJB (SSB) component that
    needs
    to
    be
    able to invoke a known method on another EJB. This second EJB may
    or
    may
    not be
    within the first JAR file but it also will be hot deployed.
    The component trying to invoke the method on the 2nd EJB has to
    be
    able to
    create
    an instance of the 2nd EJB without actually knowing anything bar
    a
    JNDI
    Name which
    is passed in at runtime.
    I can get as far as doing the
    Object home = pCtx.lookup(pJNDIName);
    This returned a class with the name
    "com.csc.edc.projects.allders.httppostoffice.postman.PostmanBean_mp8qy2_Home
    Impl_WLStub"
    My problem seems to occur when I try and invoke the create method
    Method homeCreate = home.getClass().getMethod("create", new Class[0]);
    My code throws a java.lang.NoSuchMethodException at this point so
    I
    am
    unable
    to progress to the next step of :
    Object bean = homeCreate.invoke(home, null);
    So I can return the instantiated bean back to the calling client.
    Why am I getting the NoSuchMethodException, is is because I am gettinga
    stub
    back rather than the home interface and if so how do I get the truehome
    interface
    from the bean
    Thanks in advance
    Jo Corless

  • Problems with Sandisk 16Gb microsdhc Class 2 in N8...

    Hello to you all..
    Yesterday my 16Gb microSDHC died... I wanted to charge my phone and suddenly the phone freezes and it refused to turn back on. So I decided to eject the 16Gb card and gladly I managed to turn my phone back on. So the problem was the microSDHC card. I had tested it with my PC but no response..
    This is my 2nd 16Gb card!! I never had problems with the standard 8Gb card..
    So finally I went to the shop and returned the dead card and got a refund.So now I am back to my old 8Gb card and till now everything works fine.
    But is there somebody else that had problems with a 16Gb microSDHC card in a N85 (particulary Sandisk)? Because I think the card reacted on some sort of Voltage level that he could not handle... Can this be possible?
    Black Nokia N97, productcode 0585162 FW V20.0.19 NL and 8Gb microSDHC A-data card

    hi n97fanboy
    The class thing is to do with the minimum write speed of the cards, and thus the class only describes "how good" a card is for the type of device the card is used with. Some devices require slower speed cards than others, some devices might require faster ones. Grschinon further up this thread indicated that class 2 may be too slow for the N85, and that it's minimum write speed is that of a class 4, which is the class of the micro SHDC card that the UK version of the N85 is supplied with. This makes sense.
    However, the Nokia website states that the N97 and N85 is compatible with their Class 2 16GB card, but we're not sure that this is correct given the behaviour of Sandisk Class 2 16GB cards in the device (I've had one fried, and almost lost the second one). Personally I've gone back to the 8GB Class 4 supplied with the phone, and will try and find a larger class 4 or above card at a later date.
    I'm sorry I can't help with the best card for the N97 as I've only played with the device in the Nokia Store. If it comes supplied with a microSDHC card, check for the digit on that card. If you do decide to upgrade it to a larger card, you should stick to the same class number it has or a larger one, from the experiences dkawa and myself have had with the N85. Best to try and get someone from Nokia's technical department's to confirm.
    HTH
    S.
    Black/Copper N85 sw v.30.019 Nokia 8GB Class 4 microSDHC

  • Problem with name of Servlet Class

    Hi to all,
    I have a class named AClassName and it work fine when a spider come in my web site he try to connect to the class named aclassname. I try to create a class with all lower case letter, but in windows system it's not possibile to have in the same directory a file named AClassName.class and one with the name aclassname.class
    Any help will be appreciated
    Regards
    Rinaldo

    you can solve this using servlet mapping,
    which is the correct way to call servlets,
    instead of using the invoker
    <servlet-mapping>
       <servlet-name>ListaLoc</servlet-name>
       <url-pattern>/listaloc</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
       <servlet-name>ListaLoc</servlet-name>
       <url-pattern>/ListaLoc</url-pattern>
    </servlet-mapping>

  • Thread problem with displaying to JFrame :(

    Hi everyone I have a problem, I have a JFrame which I use to submit a transaction. I am submitting a multiple number but would like to do so sequentially. SO for now i am starting one transaction thread, waiting for it to finish then starting the next etc.
    My problem is that once a transaction is finished it will not print the msg to areaOutput untill all transactions have finished processing. But the call to system.out will print at the correct time.
    I am sure i have missed a point just don't know what.
    Thread m = new Thread(transactionN);
    m.start();
    try{
    m.join();
    areaOutput.append("Finshed thread #: " + threadNum + newline);
    System.out.println("Thread done");
    }catch(InterruptedException ie){
    System.out.println("interrupted.");
    threadNum ++;Thanks for any advice!!
    luv M

    Yes, like the previous poster said. If you are running your example code from the event thread (as response to some gui-interaction like pressing a button), you are blocking the event thread. The event thread is also the same thread that paints the screen. So nothing is painted until that piece of code is finished.

  • Problem with Beansbinding as separated class

    Hello,
    I used beansbinding together with a JTextfield and usually it works, which means that if I do it like the following;
      /// the class that I use implements a binding listener
    binding = Bindings.createAutoBinding(AutoBinding.UpdateStrategy.READ_WRITE,                        // two-way binding
                                                        systemDaten ,                                                             //source and backing bean
                                                           BeanProperty.create("debeyeHueckelkonstanteA") ,          //name of field
                                                           debeyeHueckelkonstanteA,                                            // name of jtextfield as swing source
                                                           textProperty,                                                     //Property textProperty = BeanProperty.create("text");  
                                                          "debeyeHueckelkonstanteA" );                             // Name      
              binding.setConverter(null);
           binding.setValidator(null);
               binding.addBindingListener(this);                                                  /// this = because the class that I use implements a binding listener
            binding.bind();
    //if I use instead of binding.addBindingListener(this) the following version with an anonym class, it works as well:
    binding.addBindingListener(new BindingListener() {
                @Override
                public void bindingBecameBound(Binding binding) {
                @Override
                public void bindingBecameUnbound(Binding binding) {
                @Override
                public void syncFailed(Binding binding, SyncFailure failure) {
                @Override
                public void synced(Binding binding) {
                @Override
                public void sourceChanged(Binding binding, PropertyStateEvent event) {
                @Override
                public void targetChanged(Binding binding, PropertyStateEvent event) {
            } );if I use this form using a customized class and a constructor with the data (double number) to be represented :
                            binding.addBindingListener(new SystemBindingListener(systemDaten.getMesstemperatur()) )with a class implementing the listener as below it doesn't work.
    public class SystemBindingListener implements BindingListener {
        private double value = 0.0;
        public SystemBindingListener(double value) {
         super();
         this.setValue(value);
        private final PropertyChangeSupport propertyChangeSupport =
         new PropertyChangeSupport(this);
         public void addPropertyChangeListener(PropertyChangeListener l) {
         propertyChangeSupport.addPropertyChangeListener(l);
        public void removePropertyChangeListener(PropertyChangeListener l) {
         propertyChangeSupport.removePropertyChangeListener(l);
                 @Override
                    public void bindingBecameBound(Binding binding) {
                        System.out.println("bound ok " + binding.getName());  }
                @Override
                    public void bindingBecameUnbound(Binding binding) {
                        System.out.println("unbound ok " + binding.getName());  }
                @Override
                    public void syncFailed(Binding binding, SyncFailure failure) {
                        System.out.println("sync not ok " + binding.getName());  }
                @Override
                    public void synced(Binding binding) {
                    this.setValue(value);
                      System.out.println("sync ok " + binding.getName() + this.getValue()); }
                @Override
                    public void sourceChanged(Binding binding, PropertyStateEvent event) {
                        System.out.println("source ok " + binding.getName());    }
                @Override
                    public void targetChanged(Binding binding, PropertyStateEvent event) {
                        System.out.println("target ok " + binding.getName()); }
            public double getValue(){
             return value;
            public void setValue(double value){
            final double old = this.value;
         this.value = value;
         propertyChangeSupport.firePropertyChange(
                          "value", // the name of the property
                          old, // the old value
                          value // the new value
            this.value = value;
    }The problem is that I wanted to "outsource" the BindingListener but change its output depending on the source modified on the GUI.
    I have several textfields and I want to be sure that whenever one of them gets modified the value is modified in the backing bean
    and this should be visible by the System.out.println(this.getValue()) output.
    I added Property Support but this didn't help. As you can see I want a Read-Write Binding which works as described in the first two examples.
    But with a externalized class binding doesn't work.
    Does anyone know how to do this.
    Thanks for help
    Thommy
    Edited by: 886674 on 4 oct. 2011 08:31
    Edited by: 886674 on 4 oct. 2011 08:35

    Hello,
    I am not sure if it is as short as you want to, but anyway there cannot be less classes than that, because I need each of them and any further reduction
    would falsify the situation given.
    Also there are only some lines which are determining size, location - and especially Layout - etc which I left nearly as they are.
    Before using the given function addComponent() I had big problems to get a proper GUI Layout so I changed not to much concerning the layout (I didn't want to take the risk that nothing appears at all (or not at the right place) as I experienced many times before).
    Anyway, it is much less than the 10 classes (or the 30 original classes) I had before. So here is the code:
    package controls;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Toolkit;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeSupport;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import org.jdesktop.beansbinding.AutoBinding;
    import org.jdesktop.beansbinding.BeanProperty;
    import org.jdesktop.beansbinding.Binding;
    import org.jdesktop.beansbinding.Binding.SyncFailure;
    import org.jdesktop.beansbinding.BindingGroup;
    import org.jdesktop.beansbinding.BindingListener;
    import org.jdesktop.beansbinding.Bindings;
    import org.jdesktop.beansbinding.Property;
    import org.jdesktop.beansbinding.PropertyStateEvent;
    public class Main {
        public static Mainframe wg = null;
        public static void main(String[] args)  {
        wg = new Mainframe();
        wg.setVisible(true);
    class Mainframe extends JFrame {
    public static final long serialVersionUID = 1111111;
        private JPanel pnlOben;
        private JPanel pnlMitte;
        private KonstantenPanel kp = null;
        private   Dimension screendimension;
        private   Dimension dimension;   
        public Mainframe(){
        super();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        screendimension = Toolkit.getDefaultToolkit().getScreenSize();
        dimension = new Dimension();
        dimension.setSize(400, 400);
        this.setSize(dimension);
        this.setLocation((int) ((screendimension.getSize().getWidth()) / 2), (int) (screendimension.getSize().getHeight()/ 2));
        init();
    public void init(){
      desktopMalen();
    private void desktopMalen() {
             this.setLayout(new BorderLayout(20, 20));
            this.add(NordPanelMalen(), BorderLayout.NORTH);
            this.add(CenterPanelMalen(), BorderLayout.WEST);
            this.add( new JPanel(),BorderLayout.SOUTH);
        private JPanel NordPanelMalen() {
            pnlOben = new JPanel(new FlowLayout(FlowLayout.LEFT));
            pnlOben.add(new JLabel("Test"));
           return pnlOben ;
       private JPanel CenterPanelMalen() {
            this.pnlMitte = new JPanel();  //new FlowLayout(FlowLayout.CENTER
            this.pnlMitte.setLayout(new GridLayout(1, 1));    
            Dimension d = new Dimension();       
            this.pnlMitte.setSize(400,400); d.setSize(400, 400);
            KonstantenPanel bp = new KonstantenPanel(d);  //// the panel with the swing component
             this.pnlMitte.add(bp);
      return pnlMitte;
    class KonstantenPanel extends JPanel {
        public static final long serialVersionUID = 1111111;  
        private Systemdaten systemDaten = null;
        private JTextField messtemperatur;
        private BindingGroup bindinggroup = null;
        private Binding binding;
        private SystemBindingListener sbl1;
        public KonstantenPanel(Dimension d) {
        this.setSize(d);
        init();
        private void init() {
       systemDaten = new Systemdaten();           /////// the bean class
        GridBagLayout gbl = new GridBagLayout();
       this.setLayout(gbl);
        this.addComp(gbl,new JLabel("Konstanten"),0,0,4,1,0,0,GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST);
        this.addComp(gbl,new JLabel("                   "),     0,1,4,1,0,0,GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST);
        this.addComp(gbl,new JLabel("Messtemperatur   "),       0,2,2,1,0,0,GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST);
                                                                /////the swing component using beansbinding
       messtemperatur = new JTextField("298.15             ");
       messtemperatur.setName("messtemperatur");
       this.addComp(gbl,messtemperatur ,  0,3,2,1,0,0,GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST);
                                                         ///all the binding is done here in:
       bindProperties();
        @SuppressWarnings("unchecked")
            private void bindProperties() {
         Property textProperty = BeanProperty.create("text");
            bindinggroup=new BindingGroup();
         binding = Bindings.createAutoBinding(
           AutoBinding.UpdateStrategy.READ_WRITE, // two-way binding
           systemDaten,                 // bean
           BeanProperty.create("messtemperatur"),
           messtemperatur,        //field
           textProperty,        //name of property
           "messtemperatur" //name
            sbl1 = new SystemBindingListener(systemDaten.getMesstemperatur());
            binding.addBindingListener(sbl1);
            binding.setConverter(null);
         binding.setValidator(null);
             binding.bind();
             bindinggroup.addBinding(binding);
        bindinggroup.bind();
         public void addComp (   //Container cont,
                             GridBagLayout gbl, Component c, int x, int y, int width, int height, double weightx, double weighty, int cbc, int a)
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = cbc ; //GridBagConstraints.BOTH;
        gbc.gridx = x; gbc.gridy = y;
        gbc.gridwidth = width; gbc.gridheight = height;
        gbc.weightx = weightx; gbc.weighty= weighty;
        gbc.anchor = a; gbl.setConstraints(c, gbc);
        this.add(c);
         * in praxis the extra class would be especially interesting if there are more variables     *
    class SystemBindingListener implements BindingListener {
        private double value = 0.0;
        SystemBindingListener(double value) {
         super();
         this.setValue(value);
        private final PropertyChangeSupport propertyChangeSupport =     new PropertyChangeSupport(this);
        void addPropertyChangeListener(PropertyChangeListener l) {
         propertyChangeSupport.addPropertyChangeListener(l);
        void removePropertyChangeListener(PropertyChangeListener l) {
         propertyChangeSupport.removePropertyChangeListener(l);
                 @Override
                    public void bindingBecameBound(Binding binding) {
                        System.out.println("bound ok " + binding.getName());  }
                @Override
                    public void bindingBecameUnbound(Binding binding) {
                        System.out.println("unbound ok " + binding.getName());  }
                @Override
                    public void syncFailed(Binding binding, SyncFailure failure) {
                        System.out.println("sync not ok " + binding.getName());  }
                @Override
                    public void synced(Binding binding) {
                    this.setValue(value);
                      System.out.println("sync ok " + binding.getName() + this.getValue()); }
                @Override
                    public void sourceChanged(Binding binding, PropertyStateEvent event) {
                        System.out.println("source ok " + binding.getName());    }
                @Override
                    public void targetChanged(Binding binding, PropertyStateEvent event) {
                        System.out.println("target ok " + binding.getName()); }
            double getValue(){
             return value;
           void setValue(double value){
            final double old = this.value;
         this.value = value;
         propertyChangeSupport.firePropertyChange(
                          "value", // the name of the property
                          old, // the old value
                          value // the new value
            this.value = value;
    class Systemdaten {
    static final long serialVersionUID = 1111111L;
        private double messtemperatur = 298.15;
        private final PropertyChangeSupport propertyChangeSupport =     new PropertyChangeSupport(this);
       void addPropertyChangeListener(PropertyChangeListener l) {
         propertyChangeSupport.addPropertyChangeListener(l);
       void removePropertyChangeListener(PropertyChangeListener l) {
         propertyChangeSupport.removePropertyChangeListener(l);
      double getMesstemperatur() {
            return messtemperatur;
       void setMesstemperatur(double messtemperatur) {
            final double old = this.messtemperatur;
         this.messtemperatur = messtemperatur;
         propertyChangeSupport.firePropertyChange(
                          "messtemperatur", // the name of the property
                          old, // the old value
                          messtemperatur // the new value
            this.messtemperatur = messtemperatur;
    }Due to your questions I guess to know why it there is no binding between the Listener-Instance and the Swing-Compound but
    I don't see how to get all three classes working together.
    I mean: If I want to have a binding between the value variable in the BindingListener and the SwingCompound I need to create such a binding in the panel-Class.
    But I only created a binding with the field in systemDaten because this is the bean I want to work with.
    It seems that I didn't understand how it is managed that the value is changing in the bean and the swingcompound simultaneously - after creating and adding the
    BindingListener-Instance.
    In the two other cases there is still a communication between the Listener and the swingCompound but in the given case there is not.
    I was not aware of this problem before and I am still not sure to fully understand why it works in the other cases.
    Do I need to give the binding variable or swing compound to the BindingListener to keep communication ?
    Thanks for your help
    Thommy

  • Problem with threads in JFrame

    Hy everyone...i have a small problem when i try to insert clock in my JFrame , because all i get is an empty text field.
    What i do is that i create inner class that extends Thread and implements Runnable , but i dont know ... i saw some examples on the intrnet...but they are all for Applets...
    Does any one know how i can implement this in JFrame (JTextField in JFrame).
    Actually any material on threads in JFrame or JPanel would be great....THNX.

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • Problem with IconImage for JFrame

    If I create an BufferedImage by ImageIO.read for example and then call getScaledInstance on this image and set the scaled Image to a JFrame as the IconImage (via setIconImage(Image image)), the application hangs.
    Has anyone else this problem?

    ok ok, i read it and now think that this is a sscce:
    import java.awt.Image;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class Start
         public static void main(String[] args)
              final JFrame frame = new JFrame();
              final Image image, imageScaled;
              try
                   image = ImageIO.read(new File("test.png"));
                   imageScaled = image.getScaledInstance(8, 8, Image.SCALE_DEFAULT);
                   frame.add(new JLabel(new ImageIcon(image)));
                   //frame.setIconImage(image); works
                   frame.setIconImage(imageScaled); // works not
                   frame.pack();
                   frame.setVisible(true);
              catch (IOException e)
                   System.err.println(e.getMessage());
                   e.printStackTrace(System.err);
    }

  • Problem with backspace on JFrame

    Hello,
    I have a problem on a JFrame. Indeed, I add a keyListener to the frame, but the "Bakcspace" don't work. There is anything when a I press on Backspace (with KeyTyped, KeyReleased and KeyPressed). All other keys are working.
    Thanks.

    the solution of the problem is :
    Version note: This page reflects the focus API introduced in released 1.4. As of that release, the focus subsystem consumes focus traversal keys, such as Tab and Shift Tab. If you need to prevent the focus traversal keys from being consumed, you can call
    component.setFocusTraversalKeysEnabled(false)
    on the component that is firing the key events. Your program must then handle focus traversal on its own. Alternatively, you can use a KeyEventDispatcher to pre-listen to all key events. The focus page (in the Creating a GUI with JFC/Swing trail) has detailed information on the focus subsystem.

  • Problem with axis2 and QName class

    Hello,
    We have deployed AXIS2 library with a library project (J2EE server component) as it is specify by a SAP guide. We deployed the sda file correctly and we know how to reference this library in Portal Application and J2ee Module WEB or EJB.
    The problem is when we want to use internally javax.xml.namespace.QName is thrown an exception. This exception is shown bellow:
    java.lang.LinkageError: loader constraints violated when linking javax/xml/namespace/QName class
    at wpt.ConventerStub.populateAxisService(ConventerStub.java:52)
    at wpt.ConventerStub.<init>(ConventerStub.java:100)
    at wpt.ConventerStub.<init>(ConventerStub.java:89)
    at wpt.ConventerStub.<init>(ConventerStub.java:140)
    at wpt.ConventerStub.<init>(ConventerStub.java:132)
    at com.eadscasa.axis2.Axis2Converter.doContent(Axis2Converter.java:26)
    In the guide is said that we have to deploy a library project to avoid this problem but we still are getting it. I have realized that Qname class is a basic class into the JDK 1.4 and in different projects as AXIS2 making revision about this class.
    How can I deploy these libraries (jars) without dependencies with SAP Portal libraries?
    Is there any way to setup the classloader to avoid this error?
    In the documentation about this kind of project it is said that you cannot deploy libraries (*.jar) with the same name. I donu2019t know if it happens the same with the class.
    We have to develop web Services with Soap 1.2 specification, SAML etc and we need to develop this class because sap portal doesnu2019t support this kind o features.
    Regards,
    Daniel Urbano

    Hi,
    Firstly thanks for you reply. I generate the client with wsdl2java tool as it is mentioned in AXIS2 documentation and as you specified in your blog. After I follow the steps:
    Step 1 - Generating the Axis2.war
    Step 2 u2013 Modify the service *.aar file
    Step 3 u2013 Create the J2EE library
    Step 4 u2013 Create the J2EE application wrapping the web module axis2.war
    We know how to make the step 1,2 and 3 but there is a little mess in the last step. Donu2019t worry about this because we got the general idea in this document. According to the guide the main problem is to solve a classloading conflict because it only can be loaded the libraries once and you need the AXIS2 libraries for *.arr and for the axis2 engine to be able to manage this module. This problem it is solved making a J2EE library Project and putting a reference to this library in the module, applications or project, which have to use AXIS2 libraries.
    We have 3 different kind of projects that we can develop according to Sap Netweaver:
    J2EE Project:
    ·     Web Module Project: Resulting a war file.
    ·     Enterprise Application Project: Resulting a ear file
    ·     EJB Module Project: Resulting a war file.
    Portal Application
    ·     Portal Application Project: Resulting a par file.
    In any project mentioned upper we know how to deploy these with a reference to this library project that previously we deployed successfully in the portal. But the problem is when we are going to check this module running it the server give us an exception.
    java.lang.LinkageError: loader constraints violated when linking javax/xml/namespace/QName class
    at wpt.ConventerStub.populateAxisService(ConventerStub.java:52)
    at wpt.ConventerStub.(ConventerStub.java:132)
    at com.eadscasa.axis2.Axis2Converter.doContent(Axis2Converter.java:26)
    This exception is because exist classes into the axis2 libraries as javax.xml.namespace.Qname that are in SAP Portal libraries into the J2ee Server (JDK 1.4). This conflict is mentioned in the blog u201C360° View on enterprise SOAu201D where Michael Koegel, the author, says that if you want that AXIS2 libraries works you will have to work around with the dependencies of libraries.
    The main problem in this point it is that we donu2019t know how to resolve this dependencies and if it is possible that other module of SAP Portal wonu2019t work fine if we change the base libraries. AXIS2 has newer classes than SAP Portal and it is possible that we can break other SAP Portal functions. In this case if we can not get that AXIS2 and SAP Portal co-exist in the same server we will probably have to change our way to get the enterprise objectives.
    In order to resolve these dependencies we have found a SAP Note Number: 1138545. In this note it is said that we can setup the precedence class loader in the visual admin  into the deploy service. If you add your AXIS2 library at the beginning of StandardAplicationReferences variable in the deploy service, it is loaded the axis2 libraries first and it works the services but other portal functionality fails. This variable it is used to load the libraries precedence for all applications in the Server. If we could setup the class load precedence in a web module project or the system doesnu2019t take into account the server libraries for this module it will work perfectly.
    If you could specify more the last point of your manual, I will appreciate it.
    Regards,
    Daniel Urbano

  • Problem with combination of LabVIEW classes (dynamic dispatch), statechart module and FPGA module

    SITUATION:
    - I am developing a plug-in-based software with plug-ins based on LabVIEW classes which are instanced at run-time. The actual plug-in classes are derived from generic plug-in classes that define the interfaces to the instancing VI and may provide basic functionality. This means that many of the classes' methods are dynamic dispatch and methods of child classes may even call the parent method.
    - Top-level plug-ins (those directly accessed by the main VI) each have a run method that drives a plug-in-specific statechart.
    - The statechart of the data acquisition plug-in class (DAQ class) calls a method of the DAQ class that reads in data from a NI FPGA card and passes it on to another component via a queue.
    PROBLEM:
    - At higher sampling rates, an FPGA-to-host FIFO overflow occurs after some time. When I "burden" the system just by moving a Firefox browser window over the screen, the overflow is immediately triggered. I did not have this kind of problem in an older software, where I was also reading from an FPGA FIFO, but did not make use of LabVIEW classes or statecharts.
    TRIED SOLUTIONS (WITHOUT SUCCESS):
    - I put the statechart into a timed loop (instead of a simple while loop) which I assigned specifically to an own core (I have a quad-core processor), while I left all the other loops of my application (there are many of them) in simple while loops. The FIFO overflow still does occur, however. 
    QUESTION:
    - Does anybody have a hint how I could tackle this problem? What could be the cause: the dynamic dispatch methods, the DAQ statechart or just the fact that I have a large number of loops? However, I can hardly change the fact that I have dynamic dispatch methods because that's the very core of my architecture... 
    Any hints are greatly appreciated!
    Message Edited by dlanger on 06-25-2009 04:18 AM
    Message Edited by dlanger on 06-25-2009 04:19 AM
    Solved!
    Go to Solution.

    I now changed the execution priority of all the VIs involved in reading from the FPGA FIFO to "time critical priority (highest)". This seems to improve the situation very much: so far I did not get a FIFO overflow anymore, even when I move around windows on the screen. I hope it stays like this...

Maybe you are looking for

  • Office 2004 Wont Reinstall

    To tell it from the beginning. I had a bootcamp partition. I erased the partition because I had wanted to increase it in size. So then when i tried to recreate the bootcamp partition i got errors saying I need to reinstall OS X because some files cou

  • Was not copied because cannot be played on this iPod

    I am trying to load Apple Lossless Encoded files on a 2nd generation shuffle and get the paraphrased error message. Is it that the software that came with the shuffle in late 2008 can't deal with ALE files? If so, is there a place I can upgrade the s

  • Batch date change corrupts the dates

    I need some help with the batch name change in iPhoto. I recently tried to change some dates of an entire event to 12/25/2008. Once the batch change was done, the dates all appear as a corrupted year of 12/09/-2007 with the line in them. They then di

  • Weblogic EAR deployment before resource initialization

    Hi All, Our application deployment is failing while "starting all services". One of our bean is trying to obtain & initializing a queue in the ejbCreate method (bcos this is a migration project so we are not using the annotations) and it is unable to

  • Static methods. Why?

    I understand what static means, and that each class has only ONE copy of its static variables and methods. I an see the benefits of using static variables, but i cant seem to get my head round the benefits of using static methods. What is the advanta