JPanel usage

I had written an application in which, I had to move a small image, according to given values over a background image of boxes.
So, I took 2 JPanels and 2 JLabels with Images in them. First JPanel is a static JPanel (i.,e it won't changing it's position on the screen) which has an JLAbel with Image of box's on it. Second JPanel is a dynamic which changes positioning according to the values. Using this second JPanel i want to position the smaller image over a background image of boxes.
My problem is, the logic is working perfectly for intial positioning, but not working for the next values.
Can anybody help me with thislogical error.
Thank U
Sudhir

ok,,,,,,,,
can u post some code.....

Similar Messages

  • Problem with paintComponent, and CPU usage

    Hi,
    I had the weirdest problem when one of my JDialogs would open. Inside the JDialog, I have a JPanel, with this paintComponent method:
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Color old = g.getColor();
    g.setColor(Color.BLACK);
    g.drawString("TEXT", 150, 15);
    g.setColor(old);
    parent.repaint();
    now when this method is called, the CPU usage would be at about 99%. If i took out the line:
    parent.repaint();
    the CPU usage would drop to normal. parent is just a reference to the Jdialog that this panel lies in.
    Anyone have any ideas on why this occurs?
    Thanks!

    1) I never got a stack overflow, and i have had this in my code for quite sometime...If you called paint() or paintComponent(), I'm betting that you would see a stack overflow. The way I understand it, since you are calling repaint(), all you are doing is notifying the repaint manager that the component needs to be repainted at the next available time, not calling a paint method directly. good article on how painting is done : http://java.sun.com/products/jfc/tsc/articles/painting/index.html#mgr
    2) If this is the case, and the two keep asking eachother to paint over and over, .....
    see above answer

  • Simple Java 3D program’s CPU Usage spikes to up to 90 percent!

    Hi, everyone. I’m completely new to Java 3D and I’m toying around with basic program structure right now. My code is based off of that in the first chapter on 3D in Killer Game Programming in Java. I removed most of the scene elements, replacing them with a simple grid, Maya style. (Yes, I’m starting off small, but my ambitions are grand – I intend on creating a polygonal modeling and animation toolset. After all, the Maya PLE is dead – damn you, Autodesk! – and I just plain dislike Blender.) I implement a simple OrbitBehavior as a means for the user to navigate the scene. That part was basically copy and paste from Andrew Davison’s code. The mystery, then, is why the program’s framerate drops below 1 FPS and its CPU Usage spikes to up to 90 percent, according to the Task Manager, when I tumble the scene. I’d appreciate anyone taking the time to look at the code and trying to identify the problem area. (I’ve undoubtedly missed something totally newbish. -.-) Thank you!
    (Also, I had the worst possible time wrestling with the posting process. Is anyone else having trouble editing their posts before submitting them?)
    import java.awt.*;
    import javax.swing.*;
    public class MAFrame
        public static final Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit().getScreenSize();
        public MAFrame ()
            System.out.println("Initializing...");
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception e) {
                e.printStackTrace();
            JFrame frame = new JFrame ("Modeling and Animation");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            MAViewPanel panel = new MAViewPanel ();
            frame.getContentPane().add(panel);
            frame.pack();       
            frame.setLocation(((int)SCREEN_SIZE.getWidth() / 2) - (frame.getWidth() / 2),
                              ((int)SCREEN_SIZE.getHeight() / 2) - (frame.getHeight() / 2));     
            frame.setVisible(true);
    import com.sun.j3d.utils.behaviors.vp.*;
    import com.sun.j3d.utils.geometry.*;
    import com.sun.j3d.utils.universe.*;
    import java.awt.*;
    import javax.media.j3d.*;
    import javax.swing.*;
    import javax.vecmath.*;
    public class MAViewPanel extends JPanel
        public static final int GRID_SIZE = 12;
        public static final int GRID_SPACING = 4;
        public BoundingSphere bounds;
        public BranchGroup sceneBG;
        public SimpleUniverse su;
        public MAViewPanel ()
            GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
            Canvas3D canvas3D = new Canvas3D (config);               
            canvas3D.setSize(600, 600);
            add(canvas3D);
            canvas3D.setFocusable(true);
            canvas3D.requestFocus();
            su = new SimpleUniverse (canvas3D);
            createSceneGraph();
            initUserPosition();
            orbitControls(canvas3D);
            su.addBranchGraph(sceneBG);
        public void createSceneGraph ()
            sceneBG = new BranchGroup ();
            bounds = new BoundingSphere (new Point3d(0, 0, 0), 1000);
            // ambient light
            Color3f white = new Color3f (1.0f, 1.0f, 1.0f);
            AmbientLight ambientLight = new AmbientLight (white);
            ambientLight.setInfluencingBounds(bounds);
            sceneBG.addChild(ambientLight);
            // background
            Background background = new Background ();
            background.setColor(0.17f, 0.65f, 0.92f);
            background.setApplicationBounds(bounds);       
            sceneBG.addChild(background);
            // grid
            createGrid();
            sceneBG.compile();
        public void createGrid ()
            Shape3D grid = new Shape3D();
            LineArray lineArr = new LineArray (GRID_SIZE * 8 + 4, GeometryArray.COORDINATES);
            int offset = GRID_SIZE * GRID_SPACING;
            // both sides of the grid plus the middle, done for both directions at once (each line defined by two points)
            for (int count = 0, index = 0; count < GRID_SIZE * 2 + 1; count++) {
                // vertical, left to right
                lineArr.setCoordinate(index++, new Point3d (-offset + (count * GRID_SPACING), 0, offset));  // starts near
                lineArr.setCoordinate(index++, new Point3d (-offset + (count * GRID_SPACING), 0, -offset)); // ends far
                // horizontal, near to far
                lineArr.setCoordinate(index++, new Point3d (-offset, 0, offset - (count * GRID_SPACING))); // starts left
                lineArr.setCoordinate(index++, new Point3d (offset, 0, offset - (count * GRID_SPACING)));  // ends right
            grid.setGeometry(lineArr);
            sceneBG.addChild(grid);
        public void initUserPosition ()
            ViewingPlatform vp = su.getViewingPlatform();
            TransformGroup tg = vp.getViewPlatformTransform();
            Transform3D t3d = new Transform3D ();
            tg.getTransform(t3d);
            t3d.lookAt(new Point3d (0, 60, 80), new Point3d (0, 0, 0), new Vector3d(0, 1, 0));
            t3d.invert();
            tg.setTransform(t3d);
            su.getViewer().getView().setBackClipDistance(100);
        private void orbitControls (Canvas3D c)
            OrbitBehavior orbit = new OrbitBehavior (c, OrbitBehavior.REVERSE_ALL);
            orbit.setSchedulingBounds(bounds);
            ViewingPlatform vp = su.getViewingPlatform();
            vp.setViewPlatformBehavior(orbit);     
    }

    Huh. A simple call to View.setMinimumFrameCycleTime() fixed the problem. How odd that there effectively is no default maximum framerate. Of course simple programs like these, rendered as many times as possible every second, are going to consume all possible CPU usage...

  • Methods to reduce the CPU Usage for painting the image

    Hi,
    I have developed an application to view images from an IP camera. By this I can simualtaneously view images from about 25 cameras. The problem is that the CPU Usage increases as the no of player increases. My Player is JPanel. which continuously paints the images from camera. The method 'paintImage' is called from another thread's run method. This thread is responsible for taking jpeg images from IP camera.
    Here is the code for this.
    public void paintImage(Image image, int fps) {
    try {
      int width = this.getWidth();
      addToBuffer(image);
      currentImage = image;
      Graphics graphics = this.getGraphics();
      if (isRunning && graphics != null) {
       graphics.drawImage(image, 0, 0, getWidth(), getHeight(), this);
       if(border ==true){
        graphics.setColor(Color.RED);
                          graphics.drawRect(0,0,getWidth()-1, getHeight()-1);
       graphics.setColor(Color.white);
       graphics.setFont(new Font("verdana", Font.ITALIC, 12));
       graphics.drawString("FPS : " + fps, width-60, 13);
       this.fps = fps;
       if (isRandomRecord) {
        graphics.setColor(new Color(0, 255, 0));
        graphics.fillArc((getWidth() - 10), 5, 10, 10, 0, 360);
    } catch (Exception e) {
      e.printStackTrace();
    Can someone please help me to solve this problem so that the CPU usage can be reduced.

    Can you give me more detail information about how to use
    an automated profiling tool You run it and excercise your app. Then it presents stats on number of times each method was called and time spent in each method, plus other stuff. Using those two stats you can zero in on the areas that are most likely to yield resullts.

  • Help : Usage of FocusTraversalPolicy in 1.4.2_07

    Dear All,
    My existing application written in Jdk 1.3.1_15.Now,upgrading to 1.4.2_07.
    Compilation in 1.4.2_07 throws so many warnings about the deprecated method setNextFocusableComponent(Component c);
    Usage of setNextFocusableComponent
    Assume 10 components are added in a container like Panel.
    We can set the focus in random manner like comp1 ->comp3->comp5->comp4 etc.
    So, the coding will be like,
    comp1.setNextFocusablecomponent(comp3);
    comp3.setNextFocusableComponent(comp5);
    comp5.setNextFocusableComponent(comp4); etc ..etc..
    Since this particular method is deprecated in 1.4.2_07, i get warnings.
    I don't prefer this warnings and need clean compilation.
    The alternative solution is implementing FocusTraversalPolicy class.
    FocusTraversalPolicy class
    It is an abstract class has subclasses ContainerOrderFocusTraversalPolicy and InternalFrameFocusTraversalPolicy .
    I have an option to set ContainerOrderFocusTraversalPolicy to my container by the following line .
    ContainerOrderFocusTraversalPolicy CTP= new ContainerOrderFocusTraversalPolicy();
    panel.setFocusTraversalPolicy(CTP);
    The above lines of coding let componets have the sequential order of focus like comp1->comp2->comp3 etc...
    But i need to assign the random order of focus to components.
    Could anyone please help me in this regard ? what i need to do further ?
    Please help me to understand how to use this policy class for my need.Appreciate your responses.
    Sample test program
    import java.awt.*;
    import javax.swing.*;
    public class TestPanel {
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    Container content = frame.getContentPane();
    JLabel l1,l2,l3,l4,l5;
    JTextField jt1,jt2,jt3;
    JComboBox jcb1;
    JCheckBox jchb1;
    JPanel jp= new JPanel();
    l1=new JLabel();
    l1.setText("name");
    l2=new JLabel();
    l2.setText("Age");
    l3=new JLabel();
    l3.setText("Qualification");
    l4=new JLabel();
    l4.setText("Male - Yes");
    l5=new JLabel();
    l5.setText("DOB");
    jt1=new JTextField(10);
    jt2=new JTextField(20);
    jt3=new JTextField(20);
    jcb1=new JComboBox();
    jchb1=new JCheckBox();
    jp.add(l1);
    jp.add(jt1);
    jp.add(l2);
    jp.add(jt2);
    jp.add(l3);
    jp.add(jcb1);
    jp.add(l4);
    jp.add(jchb1);
    jp.add(l5);
    jp.add(jt3);
    // deprecated methods commented to avoid warnings in 1.4.2_07
    /* jt1.setNextFocusableComponent(jcb1);
    jcb1.setNextFocusableComponent(jt3);
    jt3.setNextFocusableComponent(jchb1);
    jchb1.setNextFocusableComponent(jt2);
    jt2.setNextFocusableComponent(jt1);*/
    // New policy class
    ContainerOrderFocusTraversalPolicy CTP= new ContainerOrderFocusTraversalPolicy();
    // setting the policy class in panel
    jp.setFocusTraversalPolicy(CTP);
    content.add(jp, BorderLayout.CENTER);
    frame.pack();
    frame.show();
    jp.getComponent(1).requestFocusInWindow();
    Thanks and Regards
    David Menfields

    You need to actually write your own FocusTraversalPolicy class.
    It's actually pretty easy - just subclass FocusTraversalPolicy and override all the methods. You need to have your own algorithm for determining the next/first/last/etc components and after a short look at your code my guess would be to hold a reference to each component on your form in an array in the order you want the focus to move in and then you can easily return the "next" or "previous" component by looking up the array.
    Some of the methods can call others - e.g. getDefaultComponent, getFirstComponent, and getInitialComponent usually all return the same value.
    Regards,
    Tim

  • Painting on JPanel problem

    i am new in java and im practicing on GUI...
    i wrote this stupid GUI that draw shapes on a JPanel, when i minimize the window and maximize again shapes disapear, i have been told to use the paintComponent( ) instead of getGraphics( ) but i didnt know how since my program is made out of two class...
    i will provide the code so please help a newbie
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.awt.image.RasterFormatException;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    public class can extends JFrame {
        private JPanel pic = new JPanel();
        private JButton b1 = new JButton("Clear");
        private JButton b2 = new JButton("Quit");
        private JButton b3 = new JButton("Save");
        private JRadioButton r, c, s;
        private JPanel p = new JPanel();
        public can() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(800, 600);
            setTitle("Shape Drawer");
            setLayout(new BorderLayout());
            pic.setBackground(Color.white);
            pic.addMouseListener(new locationListener());
            this.add(pic, BorderLayout.CENTER);
            this.add(b1, BorderLayout.WEST);
            this.add(b2, BorderLayout.EAST);
            this.add(b3, BorderLayout.SOUTH);
            b1.addActionListener(new clearListener());
            b2.addActionListener(new quitListener());
            b3.addActionListener(new saveListener());
            r = new JRadioButton("rectangle");
            c = new JRadioButton("circle");
            s = new JRadioButton("square");
            ButtonGroup bg = new ButtonGroup();
            bg.add(r);
            bg.add(c);
            bg.add(s);
            r.setSelected(true);
            p.add(r);
            p.add(c);
            p.add(s);
            this.add(p, BorderLayout.NORTH);
        private class saveListener implements ActionListener {
             * Invoked when an action occurs.
            public void actionPerformed(ActionEvent e) {
                saveFile();
        private class clearListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                clear();
        private class quitListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                quit();
        private class locationListener implements MouseListener {
            public void mouseClicked(MouseEvent e) {
                shapes shape = new shapes();
                Graphics g = pic.getGraphics();
                if (r.isSelected()) {
                    shape.rect(g, e.getX() - 30, e.getY() - 20);
                if (c.isSelected()) {
                    shape.circles(g, e.getX() - 25, e.getY() - 25);
                if (s.isSelected()) {
                    shape.squares(g, e.getX() - 25, e.getY() - 25);
             * Invoked when a mouse button has been pressed on a component.
            public void mousePressed(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when a mouse button has been released on a component.
            public void mouseReleased(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse enters a component.
            public void mouseEntered(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse exits a component.
            public void mouseExited(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
        private void quit() {
            System.exit(0);
        private void clear() {
            pic.repaint();
        private void saveFile() {
            int count = 1;
            String fileName = "picture.jpeg";
            File file = new File(fileName);
            if (file.exists()) {
                System.out.println("hello motto");
                fileName = "picture"+count+".jpeg";
                System.out.println(fileName);
                count++;
                System.out.println(count);
            pic = (JPanel) getContentPane();
            int w = pic.getWidth();
            int h = pic.getHeight();
            BufferedImage image = (BufferedImage) pic.createImage(w, h);
            Graphics g = image.getGraphics();
            if (g.getClipBounds() != null) {
                g.setClip(0, 0, w, h);
            pic.paint(g);
            try {
                FileOutputStream out = new FileOutputStream(file);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                encoder.encode(image);
                out.flush();
                out.close();
            } catch (IOException ioe) {
            catch (RasterFormatException rfe) {
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            } catch (Exception e) {
                System.out.println("ERROR: " + e);
            can c = new can();
            c.setVisible(true);
    }this was the first class and this is the second class that define the shapes
    import java.awt.*;
    public class shapes {
        public void squares(Graphics g, int x, int y) {
            g.setColor(Color.BLUE);
            g.fillRect(x, y, 50, 50);
        public void rect(Graphics g, int x, int y) {
            g.setColor(Color.RED);
            g.fillRect(x, y, 60, 40);
        public void circles(Graphics g, int x, int y) {
            g.setColor(Color.GREEN);
            g.fillOval(x, y, 50, 50);
    }i dunno how and where to implement the paintComponent( ) in this situation , please help me... and im also having another problemin the saveFile( ) method in the can class, it doesnt increment the naming of the file if it already exists...
    please help me...

    Hey, there were a few design issues in your code so I hope you dont mind me re-coding a few section of it to bring out the usage of the paintComponent(Graphics g) method.
    Also, the save was not working correctly because of the localization of the variables count and filename. I moved them and them global it to work. Also you had to re-create the file instance in order for it to be saved correctly with the new name.
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    public class Can extends JFrame {
        private JPanel p = new JPanel();
        private JButton b1 = new JButton("Clear");
        private JButton b2 = new JButton("Quit");
        private JButton b3 = new JButton("Save");
        private JRadioButton r, c, s;
        private PicturePanel pic = new PicturePanel();  
        private boolean shdClear = false;
        public Can() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(800, 600);
            setTitle("Shape Drawer");
            setLayout(new BorderLayout());          
            JPanel buttonPanel = new JPanel();
                buttonPanel.add(b1);
                buttonPanel.add(b2);
                buttonPanel.add(b3);
            b1.addActionListener(new clearListener());
            b2.addActionListener(new quitListener());
            b3.addActionListener(new saveListener());      
            r = new JRadioButton("rectangle");       
            c = new JRadioButton("circle");
            s = new JRadioButton("square");       
            r.setSelected(true);
            p.add(r);
            p.add(c);
            p.add(s);
            ButtonGroup bg = new ButtonGroup();
                bg.add(r);
                bg.add(c);
                bg.add(s);
            getContentPane().add(pic, BorderLayout.CENTER);
            getContentPane().add(buttonPanel, BorderLayout.SOUTH );
            getContentPane().add(p, BorderLayout.NORTH);
        public class PicturePanel extends JPanel implements MouseListener {
            Shapes shape = new Shapes();
            MouseEvent e = null;
            BufferedImage backgroundImage = null;
            public PicturePanel() {
                super();
                setBackground(Color.white);
                addMouseListener(this);
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                if(e == null) {
                    return;
                if(shdClear) {
                    backgroundImage.getGraphics().dispose();
                    backgroundImage = null;
                if(backgroundImage == null) {
                    backgroundImage = new BufferedImage( getWidth(), getHeight(),
                        BufferedImage.TYPE_INT_RGB );
                    Graphics g2 = backgroundImage.getGraphics();
                        g2.setColor( getBackground() );
                        g2.fillRect(0,0, getWidth(), getHeight());
                    // added here for performance reasons
                    // could have been added above in the if(shdClear) section 
                    if(shdClear) {
                        shdClear = false;
                        return;
                Graphics g2 = backgroundImage.getGraphics();
                if (r.isSelected()) {
                    shape.rect(g2, e.getX() - 30, e.getY() - 20);
                if (c.isSelected()) {
                    shape.circles(g2, e.getX() - 25, e.getY() - 25);
                if (s.isSelected()) {
                    shape.squares(g2, e.getX() - 25, e.getY() - 25);
                if(backgroundImage != null) {
                    g.drawImage(backgroundImage, 0, 0, this);
            public void mouseClicked(MouseEvent e) {
                this.e = e;
                pic.repaint();
             * Invoked when a mouse button has been pressed on a component.
            public void mousePressed(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when a mouse button has been released on a component.
            public void mouseReleased(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse enters a component.
            public void mouseEntered(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse exits a component.
            public void mouseExited(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
        private class saveListener implements ActionListener {
             * Invoked when an action occurs.
            public void actionPerformed(ActionEvent e) {
                saveFile();
        private class clearListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {           
                clear();
        private class quitListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                quit();
        private void quit() {
            System.exit(0);
        private void clear() {
            shdClear = true;
            pic.repaint();
        int count = 1; // moved so as not be recreated each time
        String fileName = "picture.jpeg";
        private void saveFile() {
            File file = new File(fileName);
            while (file.exists()) {
                System.out.println("hello motto");
                fileName = "picture" + count + ".jpeg";
                System.out.println(fileName);
                count++;
                System.out.println(count);
                file = new File(fileName); // recreate the file
            //pic = (JPanel) getContentPane();
            int w = pic.getWidth();
            int h = pic.getHeight();
            BufferedImage image = (BufferedImage) pic.createImage(w, h);
            Graphics g = image.getGraphics();
            if (g.getClipBounds() != null) {
                g.setClip(0, 0, w, h);
            pic.paint(g);
            try {
                FileOutputStream out = new FileOutputStream(file);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                encoder.encode(image);
                out.flush();
                out.close();
                JOptionPane.showMessageDialog(null, fileName + " Saved", "File Saved",
                JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException ioe) {
            } catch (RasterFormatException rfe) {
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            } catch (Exception e) {
                System.out.println("ERROR: " + e);
            Can c = new Can();
            c.setVisible(true);
    class Shapes {
        public void squares(Graphics g, int x, int y) {
            g.setColor(Color.BLUE);
            g.fillRect(x, y, 50, 50);
        public void rect(Graphics g, int x, int y) {
            g.setColor(Color.RED);
            g.fillRect(x, y, 60, 40);
        public void circles(Graphics g, int x, int y) {
            g.setColor(Color.GREEN);
            g.fillOval(x, y, 50, 50);
    }ICE

  • Keymap usage in Swing

    I've used <b>setKeyCode()</b>method of Keymap interface to trap key events in a <b>JTextField(in the keyPressed() method).</b>
    It's not working with Swing, but is working with AWT.(TextField)
    Anybody please get me the the details and its usage in Swing.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class sundar_ind extends JFrame implements KeyListener {
      JTextField field;
      String keyText;
      char   keyChar;
      int    keyCode;
      public sundar_ind() {
        field = new JTextField(10);
        field.addKeyListener(this);
        JPanel panel = new JPanel();
        panel.add(field);
        getContentPane().add(panel);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(200,100);
        setLocationRelativeTo(null);
        setVisible(true);
      public void keyPressed(KeyEvent e) {
        keyChar = e.getKeyChar();
        keyCode = e.getKeyCode();
        keyText = KeyEvent.getKeyText(keyCode);
        write("keyPressed");
      public void keyReleased(KeyEvent e) {
        keyChar = e.getKeyChar();
        keyCode = e.getKeyCode();
        keyText = KeyEvent.getKeyText(keyCode);
        write("keyReleased");
      public void keyTyped(KeyEvent e) {
        keyChar = e.getKeyChar();
        keyCode = e.getKeyCode();
        keyText = KeyEvent.getKeyText(keyCode);
        write("keyTyped");
      private void write(String id) {
        //if(keyText.indexOf("Unknown") != -1)
        if(keyCode == KeyEvent.VK_UNDEFINED)
          keyText = "?";
        System.out.println(id + "\tkeyText = " + keyText +
                           "\tkeyChar = " + keyChar + "\tkeyCode = " + keyCode);
      public static void main(String[] args){
        new sundar_ind();
    }

  • CPU usage goes 99% when running program

    Hi everyone.
    I have:
    - A JFrame, which acts as the main frame
    - A JPanel which is added to the JFrame
    - this JPanel draws output with paintComponent based on changes in 'model' part
    - this JPanel has a mouseListener which listens to mouse clicks, and sends to 'model' for calculation
    When my program is launched, the CPU usage goes to 99%. I checked, and found out that JPanel's paintComponent is constantly being called (i put a System.out.println to check).
    Why is it constantly being called? I thought paintComponent is called only when repaint( ) is called or when minimized or something is done.
    I don't need to keep on repainting, i'll call it myself after my 'model' finishes calculation.
    p/s i am using the model-view-controller pattern
    Can anyone tell me how to stop it from keep repainting?
    Thanks in advanced.

    I thought paintComponent is called only when repaint( ) is called or when minimized or something is done.Correct. Which means your code has introduced an infinite loop. So start debugging because we have no idea what your code looks like.

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

  • Problem with JPanel and/or Thread

    Hello all,
    I have the following problem.
    I have a JFrame containing to JPanels. The JPanels are placed
    via BorderLayout.
    JPanel #1 is for moving a little rectangle (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this button is painted in
    the top left corner of my frame. It changes if I press another button.
    Any help would be appreciated.
    Thanks.
    Ralf

    I have a JFrame containing to JPanels. The JPanels are
    placed
    via BorderLayout.The type of Layout does not seem to be relevant
    >
    JPanel #1 is for moving a little rectangle
    (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to
    do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect
    at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface
    Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this
    button is painted in
    the top left corner of my frame. It changes if I press
    another button.
    I noticed you solved this by painting the whole JFrame.
    Yeh Form time to time I get this problem too......
    Especially if the screen has gone blank - by going and having a cup of tea etc -
    Text from one Panel would be drawn in another.. annoying
    At first it was because I changed the state of some Swing Components
    not from the Event Thread.
    So make sure that your new Thread doesn't just blithely call repaint() or such like cos that leads to problems
    but rather something like
    SwingUtilities.invokeLater( new Runnable()
       public void run()
          MyComponent.repaint();
    });However I still get this problem using JScrollPanes, and was able to fix it by using the slower backing store method for the JScrollPane
    I could not see from my code how something on one JPanel can get drawn on another JPanel but it was happening.
    Anyone who could totally enlighten me on this?

  • How to give Common Background color for all JPanels in My Swing application

    Hi All,
    I am developing a swing application using The Swing Application Framework(SAF)(JSR 296). I this application i have multiple JPanel's embedded in a JTabbedPane. In this way i have three JTabbedPane embedded in a JFrame.
    Now is there any way to set a common background color for the all the JPanel's available in the application??
    I have tried using UIManager.put("Panel.background",new Color.PINK);. But it did not work.
    Also let me know if SAF has some inbuilt method or way to do this.
    Your inputs are valuable.
    Thanks in Advance,
    Nishanth.C

    It is not the fault of NetBeans' GUI builder, JPanels are opaque by default, I mean whether you use Netbeans or not.Thank you!
    I stand corrected (which is short for +"I jumped red-eyed on my feet and rushed to create an SSCCE to demonstrate that JPanels are... mmm... oh well, they are opaque by default... ;-[]"+)
    NetBeans's definitely innocent then, and indeed using it would be an advantage (ctrl-click all JPanels in a form and edit the common opaque property to false) over manually coding
    To handle this it would be better idea to make a subclass of JPanel and override isOpaque() to return false. Then use this 'Trasparent Panel' for all the panels where ever transparency is required.I beg to differ. From a design standpoint, I'd find it terrible (in the pejorative sense of the word) to design a subclass to inconsistently override a getter whereas the standard API already exposes the property (both get and set) for what it's meant: specify whether the panel is opaque.
    Leveraging this subclass would mean changing all lines where a would-be-transparent JPanel is currently instantiated, and instantiate the subclass instead.
    If you're editing all such lines anyway, you might as well change the explicit new JPanel() for a call to a factory method createTransparentJPanel(); this latter could, at the programmer's discretion, implement transparency whichever way makes the programmer's life easier (subclass if he pleases, although that makes me shudder, or simply call thePanel.setOpaque(false) before returning the panel). That way the "transparency" code is centralized in a single easy to maintain location.
    I had to read the code for that latter's UI classes to find out the keys to use (+Panel.background+, Label.foreground, etc.), as I happened to not find this info in an authoritative document - I see that you seem to know thoses keys, may I ask you where you got them from?
    One of best utilities I got from this forum, written by camickr makes getting these keys and their values very easy. You can get it from his blog [(->link)|http://tips4java.wordpress.com/2008/10/09/uimanager-defaults/]
    Definitely. I bit a pair of knucles off when discovered it monthes after cumbersomely traversing the BasicL&F code...
    Still, it is a matter-of-fact approach (and this time I don't mean that to sound pejorative), that works if you can test the result for a given JDK version and L&F, but doesn't guarantee that these keys are there to stand - an observation, but not a specification.
    Thanks TBM for highlighting this blog entry, that's the best keys list device I have found so far, but the questions still holds as to what specifies the keys.
    Edited by: jduprez on Feb 15, 2010 10:07 AM

  • 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 Firefox and very heavy memory usage

    For several releases now, Firefox has been particularly heavy on memory usage. With its most recent version, with a single browser instance and only one tab, Firefox consumes more memory that any other application running on my Windows PC. The memory footprint grows significantly as I open additional tabs, getting to almost 1GB when there are 7 or 8 tabs open. This is as true with no extensions or pluggins, and with the usual set, (firebug, fire cookie, fireshot, XMarks). Right now, with 2 tabs, the memory is at 217,128K and climbing, CPU is between 0.2 and 1.5%.
    I have read dozens of threads providing "helpful" suggestions, and tried any that seem reasonable. But like most others who experience Firebug's memory problems, none address the issue.
    Firefox is an excellent tool for web developers, and I rely on it heavily, but have now resorted to using Chrome as the default and only open Firefox when I must, in order to test or debug a page.
    Is there no hope of resolving this problem? So far, from responses to other similar threads, the response has been to deny any responsibility and blame extensions and/or pluggins. This is not helpful and not accurate. Will Firefox accept ownership for this problem and try to address it properly, or must we continue to suffer for your failings?

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

  • Problem with scanning and memory usage

    I'm running PS CS3 on Vista Home Premium, 1.86Ghz Intel core 2 processor, and 4GB RAM.
    I realise Vista only sees 3.3GB of this RAM, and I know Vista uses about 1GB all the time.
    Question:
    While running PS, and only PS, with no files open, I have 2GB of RAM, why will PS not let me scan a file that it says will take up 300Mb?
    200Mb is about the limit that it will let me scan, but even then, the actual end product ends up being less than 100Mb. (around 70mb in most cases)I'm using a Dell AIO A920, latest drivers etc, and PS is set to use all avaliable RAM.
    Not only will it not let me scan, once a file I've opened has used up "x" amount of RAM, even if I then close that file, "x" amount of RAM will STILL be unavaliable. This means if I scan something, I have to save it, close PS, then open it again before I can scan anything else.
    Surely this isn't normal. Or am I being stupid and missing something obvious?
    I've also monitored the memory usage during scanning using task manager and various other things, it hardly goes up at all, then shoots up to 70-80% once the 70ishMb file is loaded. Something is up because if that were true, I'd actually only have 1Gb of RAM, and running Vista would be nearly impossible.
    It's not a Vista thing either as I had this problem when I had XP. In fact it was worse then, I could hardly scan anything, had to be very low resolution.
    Thanks in advance for any help

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

  • Problem with JTree and memory usage

    I have problem with the JTree when memory usage is over the phisical memory( I have 512MB).
    I use JTree to display very large data about structure organization of big company. It is working fine until memory usage is over the phisical memory - then some of nodes are not visible.
    I hope somebody has an idea about this problem.

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

Maybe you are looking for

  • Difference between free space on disk and column FREE_MB in V$ASM_DISKGROUP

    Hi , in our RAC environment we have setup an ACFS. We use that mainly for RMAN backups. When connecting to the ASM instance and executing the query Select name, state, total_mb, free_mb from v$asm_diskgroup; we are getting the following result: NAME

  • Installing ODI 11 on a single server Hyperion 11.1.2.1 environment

    We have a single server Dev EPM (Hyp 11.1.2.1) environment (HP, HPCM, HFM, FDM), which is working over all fine. We now would like to use ODI for data and metadata loads. Our plan is to install ODI 11.1.1.6 on the same server where we have the above

  • BPC 10 installation

    Hello, do you have experience with BPC 10 NW installation? How long it takes to install it? Can you provide me some raw time estimation for installation and post-installation steps? My second question is about web client I saw architecture of BPC 10.

  • XI System hangs while designing BPM in correlaltion editor

    Hi, While designing BPM scenario in Integration repository, system gets hanged on pressing F4 while specifying condition in the correlation editor. Thanks and Regards Rahul Nawale

  • Ipad mini will not restore after ios update 7.1.2

    Hi Community,      I recieved a message last night about the update 7.1.2 for my ipad mini. I left my ipad on overnight while plugged in while it was updating. i woke up this morning seeing my ipad must be connected to itunes. I connect my ipad to it