Problems painting a JPanel component on a JFrame

Hi.
I've built a subclass of JPanel that has some controls on it, such as JPanels, JCheckBoxes, images, etc. I need to repaint this JPanel periodically because its contents are constantly changing.
I have it added to a main JFrame (this JFrame has also other JPanels in other locations of its content pane), and when I try to repaint this JPanel, it does not seem to be double buffered, because it momentaneously repaints other parts of the window into the JPanel region, and after that it repaints what it should.
I have tested a Panel instead of a JPanel to do the same task, and the Panel works fine.
Basically, the code is:
public class MyFrame extends JFrame
JPanel myPanel = new JPanel();
JPanel myPanel2 = new JPanel();
JPanel myPanel3 = new JPanel();
public MyFrame()
getContentPane().setLayout(null);
getContentPane().setSize(600, 400);
myPanel.setBounds(0, 0, 200, 200);
myPanel2.setBounds(0, 200, 200, 200);
myPanel3.setBounds(0, 400, 200, 100);
getContentPane().add(myPanel);
getContentPane().add(myPanel2);
getContentPane().add(myPanel3);
// javax.swing.Timer to update myPanel
Timer t = new Timer( 2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
myPanel.repaint();
t.start();
I actually use othe class names and field names, but the structure is basically the same.
Any idea of what am I doing wrong? Why Panels work fine in the same situation, into the same JFrame?
Thank you.

Try constructing your JPanels as doublebuffered then. (new JPanel(A layoutmanager, true)). The latter parameter is a boolean for creating a doublebuffered JPanel or not. Try with calling myPanel.revalidate() after repainting.

Similar Messages

  • Problem painting a JPanel

    I am making a card game for a project. The game features some human players versus some AI players. After a player makes a move, the game should take a short pause if the player was an AI player, so that the humans can see the cards played.
    Currently, the program zips by so fast after an AI move that it's not perceivable. I thought that throwing in a Thread.sleep(1000) after a call to repaint() would solve the problem. By doing this, however, I end up with a blank grey panel from the time the first AI player moves until the time it's a human's turn(at which time the executing thread dies and lets the human take over again).
    As some general information, the project is divided into a basic model/view split. A single thread of execution runs from the display to the model when a button is pressed, and the repaint is called by a callback from the model to the view. I have tried locating the sleep in different places(after the repaint, before the repaint, during AI move selection) with the same result.
    Any suggestions?

    You need to learn more about threading in swing. here is exellent chapter with example how to use timed paint in swing.
    http://developer.java.sun.com/developer/Books/javaprogramming/threads/chap9.pdf
    Here are links to articles in swing connection. You will be interested in topics about threads and using swing timer:
    http://java.sun.com/products/jfc/tsc/articles/
    It will greatly improve your app.
    Regards

  • Resolution problem when printing JPanel with picture on bg

    Hellow!
    I have some problems with printing JPanel component. I have a picture drawn on the background of the JPanel and several buttons on it. The whole JPanel is about 1600x800px. When i print whole the component with the help of PDF virtual printer, component is printed larger than A4 list. It is strange for me because print resolution is 600 dpi, so whole component must be a rectangle with the size about 2.5x1.5 inches. When I scale the graphics before painting component to fit image to page (i mean ... {color:#ff0000}g2d.scale(sc,sc); panel.paintAll(g2d);{color} ...), the picture's quality becomes very bad.
    I understod it so: I draw the component on the paper in screen resolution, then I decrease image size, so quality also decreases.
    My question is: how to draw on the graphics of printing paper the component in printers resolution (600dpi), but not in screen resolution.

    Hi there,
    Could you provide the community with a little more information to help narrow troubleshooting? What operating system?
    You can say thanks by clicking the Kudos Star in my post. If my post resolves your problem, please mark it as Accepted Solution so others can benefit too.

  • 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

  • Painting in JPanel directly

    Hi.
    Can any one help me with how to paint directly in JPanel, I need to paint directly in a swing component, but i dont know in which and how
    How i use the paintComponent method of JPanel class..
    Thanks.

    There are two ways to do this. If you are extending the JPanel class call the paintComponent method and put all your painting in there.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class ThingMie extends JPanel
    // private variables
    public ThingMie()
    // other gui stuff
    setBackground(Color.white);
    setBorder(BorderFactory.createRaisedBevelBorder());
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    // write a string
    g.setFont(new Font("Comic Sans MS", Font.PLAIN, 11));
    g.setColor(Color.red);
    g.drawString("hello", 6, 10);
    // draw a rectangle
    g.setColor(Color.green);
    g.drawRect(15, 15, 30, 60);
    // draw an ellipse
    g.setColor(Color.blue);
    g.drawOval(150, 20, 50, 100);
    public static void main(String [] args)
    JFrame thing = new JFrame();
    thing.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    thing.getContentPane().add(new ThingMie(), BorderLayout.CENTER);
    thing.setTitle("Painting to a panel");
    thing.setSize(400, 300);
    thing.setVisible(true);
    If you're creating a JPanel within another component, say a JFrame or a JDialog you can use code like this:
    import java.awt.*;
    import javax.swing.*;
    class ThingMie extends JFrame
    // private variables
    private JPanel panel;
         public ThingMie()
              setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              // other gui stuff
              panel = new JPanel()
                   protected void paintComponent(Graphics g)
                        super.paintComponent(g);
                        // write a string
                        g.setFont(new Font("Comic Sans MS", Font.PLAIN, 11));
                        g.setColor(Color.red);
                        g.drawString("hello", 6, 10);
                        // draw a rectangle
                        g.setColor(Color.green);
                   g.drawRect(15, 15, 30, 60);
                        // draw an ellipse
                        g.setColor(Color.blue);
                        g.drawOval(150, 20, 50, 100);
              panel.setBackground(Color.white);
              panel.setBorder(BorderFactory.createRaisedBevelBorder());
              getContentPane().add(panel, BorderLayout.CENTER);
         public static void main(String [] args)
              ThingMie thing = new ThingMie();
              thing.setTitle("Painting to a panel");
              thing.setSize(400, 300);
              thing.setVisible(true);
    /***********/

  • Problem with insets and placement within a JFrame.

    I have written some code that actively renders (at about 100 fps) to a JPanel contained within a JFrame. The size of the frame and the size of the panel are both set to 1000 by 700 (odd i know..)
    Everything seems to work fine and I have encountered insets before so when I am rendering I have been adjusting accordingly. However I have started to try and draw my own menu bar at the bottom of the panel and this is where I am having problems. Whatever I draw seems to be too low and disappears off the bottom. To solve this I tried getting the insets from the JFrame:
    Insets insets = getInsets();
    xAdjustmentLeft = insets.left;
    xAdjustmentRight = insets.right;
    yAdjustmentTop = insets.top;
    yAdjustmentBottom = insets.bottom;When I do this on my vista machine I get insets of 3, 3, 23, 3 accordingly. When I print out the coordinates of mouse clicks I find that at the top left corner i get 3, 23 as you would expect. When I click in the bottom right corner of my screen I get 996 (ish), 716.
    The 996 can be explained by the left inset and my bad clicking however the 716 bears no relation to the top inset of 23 or the bottom inset of 3 in any way .... I am doing something wrong or have I missed something such as by adding the JPanel to the JFrame I have added or subtracted a distance somehow?
    I ran the program on my xp machine and got similar insets of 3,3,29,3. However when I click in the bottom right of the page I get exactly the same coordinates as on the vista machine .. this just doesn't seem to make sense?
    I should probably also mention how the rendering works just incase ... I'm drawing to a VolatileImage which I then draw onto the JPanel using its own graphical context. Interestingly anything I render on the image at y coord of 0 appears correctly at the top of the screen .... which it shouldn't because of the inset ... I'm so confused.
    I hope someone can help / understand my babblings. If you need more code I can post it.. just there's rather alot of it.

    Sorry, my bad I realised I was doing some rather stupid calculations elsewhere in the program. I have now managed to get my drawn bar where I need it to be on both machines.
    However, if I am rendering a picture of 1000 by 700 and the actual screen you are seeing is something along the lines of 993 by 674 (values minus the insets) this means I am wasting time rendering a picture larger than I am actually displaying, how to be normally interpret the sizes, do they go to the very outside of the panel or the visual element inside it? I could easily just increase the JFrame itself to be larger say 1006 by 726 and have the image the exact size within that.
    Whichever way I have solved my original problem so no worries.

  • Save a "component of a JFrame to a file.  serialization

    hi there
    i read something about serialization and using the transient the example on there just using one non-serializable object . but in my case the object is going to be saved which contains : contains: String, double, Graphic, some DataSet.... etc.
    actually , i am trying to save a 'component' of a JFrame to a file, the component is a graph........... then i could load the file to do something configration (etc change the name of the graph "String", change the color....).
    but when i use the wirteObject method :
    out.writeObject(component);
    I got the NotSerializableException. I know all the objects have to be serializable in order to use the writeObject method also i know some of the component's objects aren't serialzable but it might contains a 100 of different objects??????...
    as i understand, i have to override the readObject and writeObject methods to make alll the object to serialization????? so how could i do that??? there is not just one or two objects..
    pls help
    thanks in advance

    Take a look at this stuff and see if it helps to solve your problem:
    http://java.sun.com/products/jfc/tsc/articles/persistence4/index.html
    It provides some classes, etc. on how to persist your object graph as an XML file, and then read it back in, etc.

  • Serious problem with TitledBorder(jPanel)

    I have a serious problem with TitledBorder(jPanel)
    Here, I have two class the first it contains a jTabbedPane ( class_jTabbedPane)qui call the second which contains a jPanel (Ptableau) which contains a jTable in a jPanel with TitledBorder
    The problem that one I carry out the jPanel with the title does not post
    Thank you! of your assistance.
    The source of the example is as follows:
    package jtabbedpane_titledborder;
    import java.awt.*;
    import javax.swing.*;
    public class class_jTabbedPane extends JFrame {
    PTableau PT = new PTableau();
    private JPanel jPanel1 = new JPanel();
    private JPanel jPanel2 = new JPanel();
    private JLabel jLabel3 = new JLabel();
    private JLabel jLabel2 = new JLabel();
    private JTabbedPane jTabbedPane1 = new JTabbedPane();
    public class_jTabbedPane() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    this.setSize(new Dimension(540, 515));
    jPanel1.setBackground(Color.lightGray);
    jPanel1.setBorder(BorderFactory.createEtchedBorder());
    jPanel1.setLayout(null);
    jPanel2.setBackground(new Color(27, 85, 135));
    jPanel2.setBorder(BorderFactory.createEtchedBorder());
    jPanel2.setBounds(new Rectangle(8, 7, 515, 47));
    jPanel2.setLayout(null);
    jLabel3.setFont(new java.awt.Font("Serif", 1, 25));
    jLabel3.setText("Consultation circuits");
    jLabel3.setBounds(new Rectangle(12, 12, 280, 27));
    jLabel2.setFont(new java.awt.Font("Serif", 1, 25));
    jLabel2.setForeground(SystemColor.activeCaptionBorder);
    jLabel2.setText("Consultation circuits");
    jLabel2.setBounds(new Rectangle(15, 5, 260, 32));
    jTabbedPane1.setBounds(new Rectangle(8, 62, 515, 450));
    PT.setLayout(null);
    this.getContentPane().add(jPanel1, BorderLayout.CENTER);
    jPanel1.add(jPanel2, null);
    jPanel2.add(jLabel2, null);
    jPanel2.add(jLabel3, null);
    jPanel1.add(jTabbedPane1, null);
    jTabbedPane1.add(PT,"Tableau");
    //jTabbedPane1.add(PA,"Arborescence");
    public static void main(String[] args) {
    class_jTabbedPane Ct = new class_jTabbedPane();
    Ct.setVisible(true);
    package jtabbedpane_titledborder;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.border.TitledBorder.*;
    public class PTableau extends JPanel {
    private JPanel jPanel9 = new JPanel();
    private JPanel jPanel5 = new JPanel();
    TitledBorder titledBorder5;
    TitledBorder titledBorder4;
    private JPanel jPanel4 = new JPanel();
    private JScrollPane jScrollPane2 = new JScrollPane();
    private JTable jTable1 = new JTable(4, 4 );
    private BorderLayout borderLayout1 = new BorderLayout();
    public PTableau() {
    try {
    jbInit();
    catch(Exception ex) {
    ex.printStackTrace();
    void jbInit() throws Exception {
    jPanel9.setBackground(new Color(27, 85, 135));
    jPanel9.setBorder(BorderFactory.createEtchedBorder());
    jPanel9.setBounds(new Rectangle(1, 1, 540, 350));
    jPanel9.setLayout(null);
    this.setLayout(null);
    jPanel5.setBackground(new Color(27, 85, 135));
    jPanel5.setForeground(Color.white);
    jPanel5.setBorder(BorderFactory.createEtchedBorder());
    jPanel5.setBounds(new Rectangle(12, 88, 501, 183));
    jPanel5.setLayout(borderLayout1);
    jPanel5.setBorder(titledBorder5);
    titledBorder5 = new TitledBorder(" Liste des circuits ");
    titledBorder5.setTitleColor(Color.white);
    jPanel4.setBackground(new Color(27, 85, 135));
    jPanel4.setBorder(BorderFactory.createEtchedBorder());
    jPanel4.setBounds(new Rectangle(211, 3, 291, 44));
    jPanel4.setLayout(null);
    jPanel4.setBorder(titledBorder4);
    titledBorder4 = new TitledBorder(" Liste des circuits ");
    jScrollPane2.getViewport().setBackground(Color.white);
    this.add(jPanel9, null);
    jPanel9.add(jPanel4, null);
    jPanel9.add(jPanel5, null);
    jPanel5.add(jScrollPane2, BorderLayout.CENTER);
    jScrollPane2.getViewport().add(jTable1, null);

    Create your border first, then set the panels border. Do this:
    [code]    titledBorder5 = new TitledBorder(" Liste des circuits ");
        titledBorder5.setTitleColor(Color.white);
        jPanel5.setBorder(titledBorder5);
        jPanel4.setBackground(new Color(27, 85, 135));
    //    jPanel4.setBorder(BorderFactory.createEtchedBorder()); // redundant
        titledBorder4 = new TitledBorder(" Liste des circuits ");
        jPanel4.setBorder(titledBorder4);[/code]
    Not this
    [code]    jPanel5.setBorder(titledBorder5);
        titledBorder5 = new TitledBorder(" Liste des circuits ");
        titledBorder5.setTitleColor(Color.white);
        jPanel4.setBackground(new Color(27, 85, 135));
        jPanel4.setBorder(titledBorder4);
        titledBorder4 = new TitledBorder(" Liste des circuits ");[/code]
    You should also use code tags as I have demonstrated above. It makes you code easier to read for the people you are asking to help you. You can read about them under Formatting Help on the page you post on.

  • Problem in importing ESS Component.

    Hi,
        We have problem in importing ESS component from hard drive into server.
    Here is the details
    Comaponent sap.com_SAP_ESS - 600 Level 6 Update ERP05VAL.09201316
    We are importing it through CMS. its been 2 days since we initiate import. but still running.
    Please find the log details below.
    Software Component sap.com/SAP_ESS
    Version MAIN_ERP05VAL_C.20060920131656
    Label 600 Level 6 Update ERP05VAL.09201316
    System XSSTrack-Development
    Step Repository-import
    Log /local/dsk/data1/sap/trans/EPS/in/CMSsapaudev06DD0/CMS/log/XSSTrack_D@DD0/[email protected]
    The Log file does not have any info. empty.
    Please give Ur suggestions
    Cheers,
    Senthil

    Hi,
    the problem seems to be connection to the database or may be database URL is incorrect.
    The problem can be solved via the Visual Administrator or by a manual modification of the data-sources.xml file.
    Visual Administrator --> Server --> Services  -->  JDBC Connector -->Select DataSource
    Change the URL given in the Database URL field with the appropriate one & save it.
    For step by step process refer
    http://help.sap.com/saphelp_nw04/helpdata/en/5c/2f2c4142aef623e10000000a155106/frameset.htm
    Thanks
    Swarup

  • Main component in a JFrame?

    Hi all,
    Just wondering, how do you set the main component in a JFrame (or JDialog). The main component being the component that gets activated when you hit the enter key.
    thanks,
    J

    Well, you can set the default button:
    getRootPane().setDefaultButton(...);

  • Problem adding a component into a JFrame

    public DVD_VIDEO_CLUB() {
    mainFrame = new JFrame("DVD-VIDEO CLUB");
    mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
    aDesktopPane = new JDesktopPane();
    aDesktopPane.setBackground(Color.LIGHT_GRAY);
    aDesktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    mainFrame.setContentPane(aDesktopPane);
    mainFrame.getContentPane().add(internalPanels.MainInternalPanel());
    atoolkit = Toolkit.getDefaultToolkit();
    mainFrame.addKeyListener(new MainFrameKeyListener());
    mainFrame.addWindowListener(new FrameListener());
    mainFrame.setIconImage(createFeatures.getImage());
    mainFrame.setSize(atoolkit.getScreenSize());
    mainFrame.setJMenuBar(aMenubar.MakeMenuBar(new ItemActListener()));
    mainFrame.setVisible(true);
    mainFrame.setDefaultCloseOperation(3);
    }//end constructor
    The argument internalPanels.MainInternalPanel() is a class (internalPanels) which have various jpanels
    that i want to display under certain events.
    But i don't know why the command
    mainFrame.getContentPane().add(internalPanels.MainInternalPanel());
    doesn't work? I look into the java tutorial and i have read that in order to add a component you have to
    call the command
    jframe.getContentPane().add(component);
    any help is appreciated!

    my problem isn't how to add internalframes but how to add a jpanel.Did you set the size of the JPanel?
    import java.awt.*;
    import javax.swing.*;
    public class Example {
        public static void main(String[] args) {
            JFrame mainFrame = new JFrame("DVD-VIDEO CLUB");
            mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
            JDesktopPane aDesktopPane = new JDesktopPane();
            mainFrame.setContentPane(aDesktopPane);
            JPanel p = new JPanel();
            p.add(new JLabel("here is your panel"));
            p.setLocation(100, 200); //as you like
            p.setSize(p.getPreferredSize()); //this may be what you are missing
            p.setVisible(true);
            mainFrame.getContentPane().add(p);
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainFrame.setVisible(true);
    also i have tried not write 3 but JFrame.EXIT_ON_CLOSE but i was getting an error exception continiously.Do you mean a syntax error? That constant was introduced in 1.3 -- what version are you using?

  • Help request - JFrame re-use problem - Painting issues

    Hello,
    I'll give a short background on the problem:
    The general purpose of my program is to display a series/sequence of screens in a spesific order. I have constructed an object (JFrame) for each of those screens. In the beginning I create a Vector containing information about every screen in the sequence and when the time comes for that screen to appear I use that information to create the screen.
    In my first design I created a new object for each screen (I have 6 basic types of screens but they often appear with different data - graphs and tables and such) while after I was done with a screen I released the reference to it. For some reason the memory requirement of that design were immense and kept increasing with each new screen.
    To remedy that I switched to a re-usage (recycling sort of say) design. I created a cache of screens, 1-2 of each type depending on whether two screens of the same type may appear one after the other. When a screen appears for the first time, I use the constructor to initialize it and save it in the cache but for future usage I "re-initialize" the old screen with the new data. Only after I finished re-initializng the screen I set it's visibility to true.
    Coming to the problem at last: as I understand seeing as the update of the frame's contents finishes before the screen is displayed it should already be displayed in it's updated form, BUT instead it appears with the old data for a split second and then repaints on-the-fly. You can actually see some components disappearing/appearing. This is a pretty nasty visual effect that I cant figure out how to overcome but worst of all I dont understand WHY it happens...
    **Edit:* Please read P.S. 3, just to show, this is not because I have a slow computer (it's quite new and has plenty of RAM) and I gave the heap plenty of space so it's not an issue of increasing it with each allocation
    I kindly ask for any help/advice on why the problem happens and how to fix it.
    Thank you in advance.
    P.S. I tried to pipeline the updates, say screen 1 is currently displayed so when the button to move on to screen 2 is pressed, screen 3 is re/initialized and so on. I used a seperate thread but it was synchronized with the displaying method so it should've been just like sequential updates but only less time consuming. When that didn't work I did the sequential update (which I described above) which didn't work either.
    P.S. 2. I gave the background in case it might help and to show that an advice of the sort "don't re-use and just create a new object" is out of the question =\
    P.S. 3 Something very odd I nearly forgot to mention: I work in Eclipse, and when I run it there I don't encounter this problem, it runs smoothly and there are no such painting problems but when I run it externally from the command line, that's where these problems occur and that is how the program will eventually be used. I don't understand why there is a difference at all, after all the JVM is one and the same in both cases, no? =\
    Edited by: Puchino on Dec 24, 2007 10:06 PM
    Edited by: Puchino on Dec 24, 2007 10:12 PM

    First off, It SEEMS I solved the problem by calling dispose() on the frame once I finished using it, then comes the manual updating and when I set it's visibility to true it no longer does any of weird painting problems it used to. Question is why does it work? I assumeit has something to do with the fact dispose releases the visual resources but could someone please provide a slightly more in-depth explanation?
    Second, at the moment my code doesn't have any calls to validate or invalidate or repaint (and I can't call revalidate) because JFrame doesn't inherit from JComponent. So I'd like to know please, which of these methods should I call in case I manually update the frame's contents?
    Third, I'll attempt to recreate a short sample code later on today (must be off now).
    P.S. Thanks for the replies!

  • Painting in JPanels

    Hey guys, thanks for the help with the last question. Heres another for the same program!
    So this program generates a JFrame which is populated with JPanel's in a gridLayout() format. The grid is supposed to represent a maze which is navigated by clicking on the appropriate panels.
    The first problem I'm having is trying to get the starting square, the current square and the squares that have previously stepped on to change color. Also the current square should show a circle to indicate where you are.
    Instead of doing that the squares are just showing random graphics on them due to an arbitrary line of code i put in:
    Graphics g = getGraphics();If i take that out then nothing changes color/graphics.
    The second problem I'm having is when i load a new maze (or the same one) instead of replacing the displayed one it tries to squish them both in. Yet when i print out all the values like the number of columns in the gridLayout it they are all correct. I'm hoping this is just a display error and will be fixed with the first problem.
    The Maze.java class brings everything together and calls the Walls.java class which creates and adds the JPanel's which are GridPanel.java objects. The Move.java and Maze.java alters the GridPanel's to be current or not... Good Luck =) and thanks heaps as always! YOU GUYS ARE LIFESAVERS!!!
    //Ass2.java
    public class Assign2
         public static void main(String[] args)
              Maze theMaze = new Maze();
    //Maze.java
    import java.io.*;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Maze extends JFrame
         Vector<String> data = new Vector<String>();
         GridPanel[][] panel;
         private int[] endPoints = new int[4];
         private int[] size = new int[2];
         private int moveNum;
         private int theSize;
         private int cX;
         private int cY;
         private int pX;
         private int pY;
         public Maze()
              MazeApp s = new MazeApp(this);
              moveNum = 0;
              File f = new File("maze.txt");
              readMaze(f);
         public void readMaze(File fName)
              File fileName = fName;
              Read r = new Read();
              data.clear();
              size = r.readFile(endPoints, data, fileName);
              theSize = (size[1] * size[0]);
              cX = endPoints[0];
              cY = endPoints[1];
              GridLayout layout = new GridLayout();
              layout.setRows(size[1]);
              layout.setColumns(size[0]);
              this.setLayout(layout);
              System.out.println(data.size());
              makeMaze();
         public void makeMaze()
              panel = new GridPanel [size[1]][size[0]];
              Walls w = new Walls(data, size, this);
              w.drawWalls(panel);
              panel[endPoints[1]][endPoints[0]].setStart();
              panel[endPoints[3]][endPoints[2]].setEnd();
              this.setSize(size[0]*100, size[1]*100);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setVisible(true);
         public void checkMove(Point clicked, int w, int h, int wall)
              pY = (int)(clicked.getX())/w;
              pX = (int)(clicked.getY())/h;
              Move m = new Move(cX, cY, pX, pY, w, h, wall);
              if(m.check() == 1) //MOVE NORTH
                   if((panel[cX-1][cY].checkWall() != 2) && (panel[cX-1][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 2) //MOVE SOUTH
                   if((panel[cX][cY].checkWall() != 2) && (panel[cX][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 3) //MOVE WEST
                   if((panel[pX][pY].checkWall() != 1) && (panel[pX][pY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 4) //MOVE EAST
                   if((panel[cX][cY].checkWall() != 1) && (panel[cX][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 0 )
              {JOptionPane.showMessageDialog(this, "Invalid Move! Invalid square selected!\nPlease choose an adjacent square.");}
         public void setCurrent()
              panel[cX][cY].setUsed();
              panel[pX][pY].setCurrent();
              cX = pX;
              cY = pY;
              moveNum++;
              if(cY == endPoints[2] && cX == endPoints[3])
              {JOptionPane.showMessageDialog(this, "Congratulations!\nYou finished in" + moveNum + "moves!");}
    // MazeApp.java
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    public class MazeApp extends JFrame
           private Maze theMaze;
           public MazeApp(Maze m)
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   theMaze = m;
                   // create the menu bar to hold the menus...
                   JMenuBar menuBar = new JMenuBar();
                   // create the menus to hold the menu items...
                   JMenu menuFile = new JMenu("File");
                   JMenu menuOptions = new JMenu("Options");
                   JMenu menuHelp = new JMenu("Help");
                   // create file menu options:
                   JMenuItem itemLoad = new JMenuItem("Load");
                   JMenuItem itemSaveAs = new JMenuItem("Save As...");
                   JRadioButtonMenuItem itemModePlay = new JRadioButtonMenuItem("Play");
                   JRadioButtonMenuItem itemModeEdit = new JRadioButtonMenuItem("Edit");
                   JMenuItem itemExit = new JMenuItem("Exit");
                   //create options menu:
                   JRadioButtonMenuItem itemNoRats = new JRadioButtonMenuItem("No Rats");
                   JRadioButtonMenuItem itemOneRat = new JRadioButtonMenuItem("One Rat");
                   JRadioButtonMenuItem itemTwoRats = new JRadioButtonMenuItem("Two Rats");
                   //create help option:
                   JMenuItem itemHelp = new JMenuItem("Help");
                   JMenuItem itemAbout = new JMenuItem("About");
                   //set default options:
                   itemModePlay.setSelected(true);                    
                   itemNoRats.setSelected(true);
                   // add File options:
                   menuFile.add(itemLoad);
                   menuFile.add(itemSaveAs);
                   menuFile.addSeparator();
                   menuFile.add(itemModePlay);
                   menuFile.add(itemModeEdit);
                   menuFile.addSeparator();
                   menuFile.add(itemExit);
                   //add Options:
                   menuOptions.add(itemNoRats);
                   menuOptions.add(itemOneRat);
                   menuOptions.add(itemTwoRats);
                   //add Help options:
                   menuHelp.add(itemHelp);
                   menuHelp.add(itemAbout);
                   // add the menu to the menu bar...
                   menuBar.add(menuFile);
                   menuBar.add(menuOptions);
                   menuBar.add(menuHelp);
                   // finally add the menu bar to the app...
                   m.setJMenuBar(menuBar);
                   //listeners
                   itemExit.addActionListener(
                           new ActionListener()
                                   public void actionPerformed( ActionEvent event )
                                           System.exit( 0 );
                itemLoad.addActionListener(
                   new ActionListener()
                        public void actionPerformed( ActionEvent event )
                             final JFileChooser fc = new JFileChooser();
                             int returnVal = fc.showOpenDialog(MazeApp.this);
                          File fileName = fc.getSelectedFile();
                             if(fileName.exists())
                                  theMaze.readMaze(fileName);
                             else
                                  System.out.println("404. File not found");
                   itemAbout.addActionListener(
                           new ActionListener()
                                   public void actionPerformed( ActionEvent event )
                                           //do stuff
                                           JOptionPane.showMessageDialog(MazeApp.this, "Author: Pat Purcell\[email protected]", "About", JOptionPane.ERROR_MESSAGE);
    //Read.java
    import java.io.*;
    import java.util.Vector;
    public class Read
         private BufferedReader input;
         private String line;
         private String fileName;
         private String[] temp;
         private int[] size = new int[2];
         public int[] readFile(int[] endPoints, Vector<String> data, File fileName)
              try
                   data.clear();
                   FileReader fr = new FileReader(fileName);
                   input = new BufferedReader(fr);
                   line = input.readLine();
                   temp = line.split("\\s");
                   for(int i =0;i<2;i++)
                   {size[i] = Integer.parseInt(temp);}
                   line = input.readLine();
                   temp = line.split("\\s");
                   for(int i =0;i<4;i++)
                   {endPoints[i] = Integer.parseInt(temp[i]);}
                   line = input.readLine();
                   while (line != null)
                        String[] temp = line.split("\\s");
                        for(int i=0;i<size[0];i++)
                             data.addElement(temp[i]);
                        line = input.readLine();
                   input.close();
              catch (IOException e)
                   System.err.println(e);
              return size;
    }//Walls.java
    import java.util.Vector;
    import java.awt.GridLayout;
    import javax.swing.*;
    public class Walls extends JFrame
         private Vector<String> data = new Vector<String>();
         private int size;
         private Maze bm;
         private int row;
         private int column;
         public Walls(Vector<String> theData, int[] theSize, Maze m)
              data = theData;
              row = theSize[1];
              column = theSize[0];
              size = row*column;
              bm = m;
         public boolean testEast(int position)
              boolean exists;
              String temp = data.get(position);
              int eastData = ((int)temp.charAt(0) - (int)'0');
              if(1 == (eastData))
                   return true;
              return false;
         public boolean testSouth(int position)
              boolean exists;
              String temp = data.get(position);
              int southData = ((int)temp.charAt(1) - (int)'0');
              if(1 == (southData))
                   return true;
              return false;
         public boolean testBoth(int position)
              boolean exists;
              if((testEast(position) && testSouth(position)) == true)
                   return true;
              return false;
         public void drawWalls(GridPanel panel[][])
              int i = 0;
              for(int y=0;y<row;y++)
                   for(int x=0;x<column;x++, i++)
                   if (testBoth(i) == true)
                   {     GridPanel temp = new GridPanel(3, bm);
                        panel[y][x] = temp;
                                  bm.add(temp);}
                   else{
                        if (testEast(i) == true)
                        {     GridPanel temp = new GridPanel(1, bm);
                             panel[y][x] = temp;
                                  bm.add(temp);}
                        else{
                             if (testSouth(i) == true)
                             {     GridPanel temp = new GridPanel(2, bm);
                                  panel[y][x] = temp;
                                  bm.add(temp);}
                             else{
                                  GridPanel temp = new GridPanel(0, bm);
                                  panel[y][x] = temp;
                                  bm.add(temp);}
    }//GridPanel.java
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class GridPanel extends JPanel implements MouseListener
    private int wall;
    private Maze bm;
    private Ellipse2D.Double circle = new Ellipse2D.Double();
    private Graphics gr;
    boolean current = false;
    boolean start = false;
    boolean finish = false;
    public GridPanel(int theWall, Maze m)
         wall = theWall;
         this.addMouseListener(this);
         bm = m;
         public void paintComponent(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              g2.setStroke(new BasicStroke(1));
              g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
              g2.setStroke(new BasicStroke(4));
              if(wall == 0) //NO WALL
              if(wall == 1) //EAST WALL
                   g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              if(wall == 2) //SOUTH WALL
                   g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
              if(wall == 3) //BOTH WALLS
                   g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
                   g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              if(current == true)
                   setBackground(SystemColor.green);
                   circle = new Ellipse2D.Double();
                   circle.x = 0;
                   circle.y = 0;
                   circle.height = this.getHeight()-1; // -1 so it fits inside the panel.
                   circle.width = this.getWidth()-1;
                   g2.draw(circle);
                   repaint();
              if(start == true)
              {     setBackground(SystemColor.green);
                   g2.drawString("S", this.getWidth()/2, this.getHeight()/2);}
              if(finish == true)
              {     setBackground(SystemColor.green);
                   g2.drawString("F", this.getWidth()/2, this.getHeight()/2);}
         public int checkWall()
              return wall;
         public void setCurrent()
              Graphics g = getGraphics();
              repaint();
         public void setUsed()
              current = false;
              repaint();
         public void setStart()
              start = true;
              repaint();
         public void setEnd()
              finish = true;
              repaint();
         public void mouseClicked(MouseEvent e){bm.checkMove(this.getLocation(), this.getWidth(), this.getHeight(), wall);}
         public void mouseReleased (MouseEvent e) {}
         public void mouseEntered (MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mousePressed(MouseEvent e) {}
    }//Move.java
    import java.awt.*;
    public class Move
         private int pX;
         private int pY;
         private int cX;
         private int cY;
         private int w;
         private int h;
         private int wall;
         public Move(int x1, int y1, int x2, int y2, int theWidth, int theHeight, int wallCheck)
              pX = x2;
              pY = y2;
              cX = x1;
              cY = y1;
              w = theWidth;
              h = theHeight;
         public int check()
              //System.out.println(cX + " " + (pX + 1));
              if((cX == (pX + 1)) && (cY == pY)) //MOVE NORTH
              {return 1;}
              //System.out.println(cX + " " + (pX - 1));
              if((cX == (pX - 1)) && (cY == pY)) //MOVE SOUTH
              {return 2;}
              //System.out.println(cY + " " + (pY + 1));
              if((cY == (pY + 1)) && (cX == pX))//MOVE WEST
              {return 3;}
              //System.out.println(cY + " " + (pY - 1));
              if((cY == (pY - 1)) && (cX == pX))//MOVE EAST
              {return 4;}
              return 0;
    }This is the file the maze is read out of: Maze.txt6 5
    0 0 3 2
    10 00 01 01 01 10
    10 10 00 01 10 10
    10 10 01 11 10 10
    10 01 01 01 11 10
    01 01 01 01 01 11                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    -> Second proplem that still remains is the circle stays after you leave the square...
    Thats why I suggested you use a Border and not do custom painting. There is no such method as remove(...). You need to repaint the entire panel. If you use a Border you just use setBorder(...) to whatever. So you have two different Borders. One for when the component has focus and one for when the component doesn't.
    -> but the same two problems remain.
    Well, I don't know whats wrong and I am not about to debug your program since I have no idea what it is doing. So create a SSCCE to post.
    see http://homepage1.nifty.com/algafield/sscce.html,
    Basically all you need to do is create a JFrame. Create a "main" panel with a flow layout and add it to the content pane. Then create 3 or 4 panels with a default Border on a black line and add the panels to the "main" panel. Then add you MouseListeners and FocusListeners to the panels. The whole program should be 30 lines of code or so. Understand how that program works and then apply the same concepts to you real program.
    The point is when you attempt to do something new that you don't understand write a simple program so you can prove to yourself that it works. If you can't get it working then you have a simple SSCCE to post and then maybe someone will look at it.

  • Painting in JPanel with PaintComponent.

    Hi I've got a problem, if i define my JPanel like this then I can't paint in it.
    public class kvadrat
    JPanel aPanel;
    public void Panel()
      aPanel = new JPanel();
      aPanel.setBackground(Color.white);
      aPanel.add(sendButton);
    public void Frame()
      Panel();
      JFrame frame = new JFrame("Considerate Music");
      Container iRutan = frame.getContentPane();
      iRutan.setLayout(new BorderLayout());
      iRutan.add(aPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setBounds(300,300,700,400);
      frame.setVisible(true);
    public kvadrat()
      Frame();
    public static void main(String[] args)
      new kvadrat();
    public void paintComponent(Graphics g)
    }I can't use the line super.paintComponent(g); in paintComponent because I don't have any extend. I don't want to have any extends on my class so this is why I'm asking, is there a way to paint on my panel(aPanel) in any other way that using extends. You see if I'd like to add more panels I'll have to create a class for each panel and I don't like that.

    2 Ways.
    #1: An Inner Class
    public class kvadrat{
    public kvadrat(){
    new MyPanel();
    //inner class
    public class MyPanel extends JPanel{
    // methods
    }or
    #2: Anonymous Inner Classes (very sloppy)
    public class kvadrat
    JPanel aPanel;
    public void Panel()
    // right here:
      aPanel = new JPanel(){
           public void paintComponent(Graphics g){
      // code goes here
      aPanel.setBackground(Color.white);
      aPanel.add(sendButton);
    public void Frame()
      Panel();
      JFrame frame = new JFrame("Considerate Music");
      Container iRutan = frame.getContentPane();
      iRutan.setLayout(new BorderLayout());
      iRutan.add(aPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setBounds(300,300,700,400);
      frame.setVisible(true);
    public kvadrat()
      Frame();
    public static void main(String[] args)
      new kvadrat();
    // removed: public void paintComponent(Graphics g)
    }

  • Painting with JPanel

    I have many classes, but only 3 matter. The problem is that my JPanel will not repaint. I tried using the repaint method, but it won't go to paintComponent.
    My main class is:
    package MainClass;
    * Main.java
    * Created on January 25, 2007, 5:05 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author Wizardus
    import Graphics.*;
    import Utilities.*;
    import Loading.*;
    import java.util.Vector;
    import MainClass.*;
    public class Main {
        public Frame frame;
        public MenuListener listen;
        public String currMode;
        public String tmpFileName;
        public GWInterface gwi;
        public Loader load;
        public Vector stuffs;
        /** Creates a new instance of Main */
        public Main() {
            listen = new MenuListener(this);
            frame = new Frame(this);
            frame.addKeyListener(listen);
        public void newGame() {
            gwi = new GWInterface(false, false);
            Loader load = new Loader();
            //Campaign camp = load.loadCampaign("someone");
            currMode = "GAME";
            frame.updateStage(currMode);
            //Map mp = load.loadMap(camp.mapFile);
            //stuffs = load.loadStuff(camp.stuffFile);
            Map mp = load.loadMap("someone.gwmp");
            stuffs = load.loadStuff("someone.gws");
            //AIType ai = load.loadAI(camp.aiFile);
            //gwi.ai = ai;
            gwi.idLoaded(0);
            gwi.mapLoaded(mp);
            gwi.loadUp(stuffs);
            frame.removeKeyListener(listen);
            frame.addKeyListener(gwi);
            frame.addMouseListener(gwi);
            frame.addMouseMotionListener(gwi);
            gameLoop();
        public void gameLoop() {
            while(true) {
                gwi.update();
                //gwi.ai();
                frame.updateDisp();
                System.out.println("Hi in gameLoop");
                try {
                    Thread.sleep(50);
                } catch(Exception e) {
        public static void main(String[] args) {
            new Main();
    }The actual JFrame is called Frame:
    * Display.java
    * Created on January 30, 2007, 8:44 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package Graphics;
    * @author Wizardus-
    import Utilities.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.*;
    import MainClass.*;
    import java.util.Vector;
    import Utilities.Build.*;
    import Utilities.Troops.*;
    public class Frame extends JFrame{
        Main mana;
        public MainPanel panel;
        /** Creates a new instance of Display */
        public Frame(Main mana) {
            super("Something something");
            this.mana = mana;
            panel = new MainPanel(mana);
            panel.loadUp();
            getContentPane().add(panel);
            setSize(1000, 700);
            setVisible(true);
        public void updateDisp() {
            System.out.println("Hi in updateB");
            panel.updateDisp();
        public void updateStage(String stage) {
            panel.updateStage(stage);
    }Then, the JPanel called MainPanel is:
    * Display.java
    * Created on January 30, 2007, 8:44 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package Graphics;
    * @author Wizardus-
    import Utilities.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.*;
    import MainClass.*;
    import java.util.Vector;
    import Utilities.Build.*;
    import Utilities.Troops.*;
    public class MainPanel extends JPanel{
        String stage = "MENU";
        //BufferStrategy img;
        Main mana;
        Image backgroundDesign;
        Image panel;
        Image[] units;
        Image[] buildings;
        Image[] terrains;
        /** Creates a new instance of Display */
        public MainPanel(Main mana) {
            super();
            this.mana = mana;
            setSize(1000,700);
            setVisible(true);
        public void loadUp() {
            //createBufferStrategy(2);
            //img = getBufferStrategy();
            loadImg();
        public void loadImg() {
            //load the crap images!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! YEAH
        public void updateDisp() {
            System.out.println("Hi in updateA");
            repaint();
        public void updateStage(String stage) {
            this.stage = stage;
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            System.out.println("painting...");
            //Graphics g = img.getDrawGraphics();
    //        System.out.println(stage);
            if(stage.equals("MENU")) {
    //            //draw menu and menu's buttons
            } else if(stage.equals("GAME")) {
    //            //draw EVERYTHING in game
    //            //Step 0 draw map and background for panels
    //            g.drawImage(panel, 700, 0, null);
    //            g.drawImage(backgroundDesign, 690, 0, null);
    //            Map mp = mana.gwi.offmap;
    //            for(int i = 0; i < mp.terrain.length; i++) {
    //                for(int j = 0; j < mp.terrain.length; j++) {
    // Terrain curr = mp.terrain[i][j];
    // g.drawImage(terrains[curr.nameId], (mp.terrain.length * 15) + mana.gwi.mapX, (mp.terrain[i].length * 15) + mana.gwi.mapY, null);
    // //Step 1 draw buttons;
    // for(int i = 0; i < mana.gwi.defButtons.length; i++) {
    // g.drawRect(mana.gwi.defButtons[i].x, mana.gwi.defButtons[i].y, mana.gwi.defButtons[i].width, mana.gwi.defButtons[i].height);
    // g.drawString(mana.gwi.defButtons[i].txt, mana.gwi.defButtons[i].x, mana.gwi.defButtons[i].y);
    // for(int i = 0; i < mana.gwi.currButtons.length; i++) {
    // g.drawRect(mana.gwi.currButtons[i].x, mana.gwi.currButtons[i].y, mana.gwi.currButtons[i].width, mana.gwi.currButtons[i].height);
    // g.drawString(mana.gwi.currButtons[i].txt, mana.gwi.currButtons[i].x, mana.gwi.currButtons[i].y);
    //Step 2 draw units of each "Stuff" and the buildings;
    for(int i = 0; i < mana.gwi.stuff.size(); i++) {
    Stuff currStuff = (Stuff)mana.gwi.stuff.get(i);
    // for(int j = 0; j < currStuff.buildings.size(); j++) {
    // Buildings currBuild = (Buildings)currStuff.buildings.get(j);
    // g.drawImage(buildings[currBuild.nameId], (int)currBuild.x, (int)currBuild.y, null);
    for(int j = 0; j < currStuff.troops.size(); j++) {
    Soldier currSold = (Soldier)currStuff.troops.get(j);
    //g.drawImage(units[currSold.nameId], (int)currSold.x, (int)currSold.y, null);
    g.drawRect((int)(currSold.x), (int)(currSold.y), 20,20);
    //img.show();

    Thats because in your gameLoop you use Thread.sleep(...) which causes the GUI Thread to sleep. If the thread is sleeping then it never gets a chance to repaint itself.
    If you want you game to repaint itself then use a [url http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html]Swing Timer to schedule the repainting and get rid of the Thread.sleep(..).

Maybe you are looking for

  • Error DBIF_RSQL_SQL_ERROR and DBIF_REPO_SQL_ERROR while running DTP

    Hi to all, I am loading the data from PSA to DSO, while running DTP, after some records load a run time error coming DBIF_RSQL_SQL_ERROR or DBIF_REPO_SQL_ERROR . Also i tried the Number of Processes reduce from 3 to 1 in DTP, but still same error . i

  • How to include WAD objects in BSP

    Hi, I would love it if I could include WAD objects like tables, maps, etc. directly in a BSP page - Is this possible ?

  • Lenovo Windows 7 Upgrade questions (please help)

    Dear Lenovo Community: I recently purchased a Thinkpad T500 and signed up for the Lenovo Windows 7 Upgrade Program.  I have a few questions that I haven't been able to find the answers to elsewhere.  I was hoping some of you could help: 1) Will the L

  • So many INACTIVE sessions in Database

    Hi, Actually PMON will clears all inactive sessions from database. But i can see there are sessions like more then 3,4 days old. Why PMON is not clearing them. ? On which intervals will PMON do inactive sessions cleaning. thanks in Advance.

  • Site License query ...

    How much will it cost the school I work at to license Adobe CC for a site license?