Paint background of a JDialog

Hey,
i have a quite simple problem: I want to paint the background of my own JDialog, but i dont know how. I looked for a method like paintComponent(Graphics g) like in a JPanel, but there is no function. So i overwrite the method paint(Graphics g) but this doesnt work because my JList and JButtons on the dialog won?t be shown anymore.
Any idea? Thanks a lot.
Ohnoooooo!

OhNo wrote:
i have a quite simple problem: I want to paint the background of my own JDialog, but i dont know how. I looked for a method like paintComponent(Graphics g) like in a JPanel, but there is no function. On looking through the forum, I've found threads such as this one:
http://forum.java.sun.com/thread.jspa?threadID=5257250&tstart=30
Where it is recommended to do custom painting in a BufferedImage, then draw the BufferedImage in a JPanel's paintComponent override. Then add your JList, JButtons, and whatnot to the same JPanel. And then finally add the JPanel to the contentPane of the JApplet and you should be good to go.
Many here have their GUI programs produce a JPanel as the final product. This increases flexibility quite a bit, since if the GUI is needed as a JFrame, simply add the JPanel to a JFrame, if a dialog, add the panel to a JDialog, and finally if a JApplet is needed, simply add the JPanel to the JApplet.
Good luck!

Similar Messages

  • Difficulties while painting (Background shown in front of my painting)

    Hi,
    First of all, I just want to tell you i'm a noob in JAVA (used to do C++). I just learned it in a one week crash auto-didacte course and i'm coding for almost a month now so it is certain that I'm missing something obvious.
    I read the painting tutorial, and I cant find my answer. Here what's happening
    I have 3 classes. One does all the calculation of the position of the points i'll need. The second one (the UI) takes care of the Frame of my application and add the buttons, borders, etc... It also had a 2 panels. One containing my buttons and one containing my painting area. The third one is giving me some hard time. This classes has the job to communicate with the 2 others. I listen to the first one in the case I have an uptdate of coordinates and I has to draw the points It receives from the first one on the panel of the second one.
    When I load up my application, my points are all where they should. However, I realized that when my windows go to the background, is minimized or is resized, the background is show in front so I cant see my points anymore. I used a componentListener to test if I could repaint my things on top of the background and it didn't work... Here is my code for the third classe.
    public class test extends JPanel
         public void paintit(BarycentreModel test_model, BarycentreUI test_UI)
              System.out.println("Inside test.paint()");
              Graphics g = test_UI.getBarycentrePanel().getGraphics();
              g.setColor(Color.YELLOW);
              g.fillRect(0,0,600,600);
              test_UI.getBarycentrePanel().getGraphics().setColor(Color.BLUE);
              for(int i=0; i < test_model.get_maxsoldats(); i++)
                   test_UI.getBarycentrePanel().getGraphics().fillOval((int)test_model.getCoordinates().x, (int)test_model.getCoordinates()[i].y,
                                  test_model.get_diametresoldat(), test_model.get_diametresoldat());
                   //SoldierInfo soldierinfo = new SoldierInfo((SoldierInfo)test_model.getCoordinateSoldierInfoMap().get(test_model.getCoordinates()[i]));
         public static void main(String[] args)
              final BarycentreModel test_model = new BarycentreModel();
              test_model.setRandomParameters(10,4,5,new Dimension(590,500));
              final BarycentreUI test_UI = BarycentreUI.getInstance();
              final test test1 = new test();
              test1.paintit(test_model, test_UI);
              test_UI.getBarycentrePanel().addComponentListener(new ComponentAdapter()
                   public void componentResized(ComponentEvent e)
                             System.out.println("WINDOW RESIZED DAMNIT");
                             test1.paintit(test_model, test_UI);
    I tried to used the repaint() ,repaint() or paintcomponent() method to do it but couldnt see how to do it.
    Can anyone point me to a tutorial that explain this or better, help me manage to make my paintit() methode paint after the background has been refreshed.

    Check out repl#5, etc... http://forum.java.sun.com/thread.jsp?forum=54&thread=529542
    (The punch line is that you should avoid Component's getGraphics.)

  • Painting background of transparent icon

    I have an ImageIcon that came from a transparent gif. Is there a way to control how the background color is painted, for example setting the background to red or white? Thanks.

    That's one way to do it but it may not be appropriate - eg the component may have an empty border, it may contain other content, it doesn't alter the icon when displayed elsewhere, etc.
    If you want to cook a new icon then:
    1. create an image of the same size
    2. get the graphics object from it
    3. fill the graphics with the chosen background color
    4. draw the original image onto the graphics
    5. create a new ImageIcon using this new image

  • Jdialog paint

    How does the painting work on a JDialog window ? I am opening a JDialog on clicking a button and on that Jdialog has 2 jpanels. one with a jbutton and other panel for just painting a image. on the top of the image the user can draw rectangles. where should i put the code for mousedragged event ??

    here is my code. please run after replacing the image URL. I ned to draw rectangles on top of the image...it draws but something is not right
    import java.net.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    class MapDialog extends JDialog implements MouseMotionListener{
         JButton btnMap,btnCancel;
         JLabel lblImage;
         JPanel pnlButtons,pnlImage;
         Image  im;
         int locationx,locationy;
         int startx,starty;
         boolean bIsMouseDragged;
         int counter;
         int rectPoints[];
         int iRectCounter;
         String[] strCoords;
         public MapDialog() {
              rectPoints = new int[200];
              strCoords = new String[200];
              addMouseMotionListener(this);
                   MyMouseListener mml = new MyMouseListener();
                   addMouseListener(mml);
                   pnlButtons = new JPanel();
                   pnlImage = new JPanel();
                   btnMap = new JButton("Save");
                   btnCancel = new JButton("Cancel");
                   pnlButtons.add(btnMap);
                   pnlButtons.add(btnCancel);
                   getContentPane().add(pnlImage, BorderLayout.CENTER);
                   getContentPane().add(pnlButtons, BorderLayout.SOUTH);
                   pack();
                   Toolkit tk = Toolkit.getDefaultToolkit();
                   Dimension d = tk.getScreenSize();
                   setLocation(((int)d.getWidth() /2 ) - getWidth() / 2  , ((int)d.getHeight() / 2) - getHeight() / 2);
              public void paint(Graphics g) {
                             System.out.println("paint called");
                             validate();
                             super.paint(g);
         public void paintComponents(Graphics g) {
              System.out.println("pc called");
              Graphics g2 = pnlImage.getGraphics();
              try {
                             URL url = new URL("http://localhost/java/mapedit2/images/leftart.jpg");
                             im = Toolkit.getDefaultToolkit().getImage(url);
                             MediaTracker mt = new MediaTracker(this);
                             mt.addImage(im, 0);
                             try {
                                  mt.waitForAll();
                             } catch (InterruptedException e) {}
                        } catch(MalformedURLException ure) {System.out.println("exception");}
              g2.drawImage(im,0,0,this);
              if( bIsMouseDragged) {
                                  g2.drawLine(startx,starty,locationx,starty);
                                  g2.drawLine(startx,starty,startx,locationy);
                                  g2.drawLine(startx,locationy,locationx,locationy);
                                  g2.drawLine(locationx,starty,locationx,locationy);
         //     g2.dispose();
         public void mouseDragged(MouseEvent me) {
                             locationx = me.getX();
                             locationy = me.getY();
                             bIsMouseDragged = true;
                             repaint();
                        public void mouseMoved(MouseEvent me) {
                                       //System.out.println(me.getX());
              class MyMouseListener extends MouseAdapter {
                             public void mousePressed(MouseEvent me) {
                                            startx = 0;
                                            starty = 0;
                                            locationx = 0;
                                            locationy = 0;
                                            System.out.println("start X : " + me.getX());
                                            System.out.println("start Y : " + me.getX());
                                            startx = me.getX();
                                            starty = me.getY();
                                            //repaint();
                             public void mouseReleased(MouseEvent me) {
                                  int rectWidth = (int) Math.sqrt( (locationx - startx) * (locationx - startx));
                                  int rectHeight = (int) Math.sqrt( (locationy - starty) * (locationy - starty));
                                  System.out.println("iRectCounter " + iRectCounter);
                                  rectPoints[iRectCounter] = startx;
                                  rectPoints[iRectCounter+1] = starty;
                                  rectPoints[iRectCounter+2] = rectWidth;
                                  rectPoints[iRectCounter+3] = rectHeight;
                                  iRectCounter += 4;
                                  System.out.println("end X : " + me.getX());
                                  System.out.println("end Y : " + me.getX());
                                  bIsMouseDragged = false;
                                  // THIS IS THE LINE THAT POPS UP THE HTTP ENTERING VALUE
                                  //AddlinkDialog2 aldialog = new AddlinkDialog2(ImagePanel.this, true);
         public static void main(String[] args) {
              //JFrame frame = new JFrame();
              //frame.add(
              MapDialog md = new MapDialog();
              md.pack();
              md.setVisible(true);
              md.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
         }

  • How do i set the background of the table( not of cell / row / column).

    How do i set the background of the table( not of cell / row / column).
    What happens when i load the applet the table is blank and displays the background color is gray which we want to be white.
    We tried using the setBackGround but it is not working maybe we are not using it properly. Any help would be gr8.
    Thanks in advance.

    I don't understand very well, but i guess that the background is gray when the table content's empty, isn't it?
    When the table model is empty, the JTable doesn't paint, so its container displays its background (often gray).
    In this case, what you must do is force the table to paint, even if the model is empty. So, you have to create your own table and override three methods :
    public class MyTable extends JTable
    //specify the preferred and minum size when empty
    myPreferredWidth = 200;
    myPreferredHeigth =200;
    myMinimunWidth = ...;
    myMinimunHeigth = ...;
    public Dimension getPreferredSize()
    if(getModel().getRowCount() < 1)
    return new Dimension(myPreferredWidth, myPreferredHeigth);
    else
    return super.getPreferredSize();
    public Dimension getMinimumSize()
    if( getModel().getRowCount() > 0)
    return new Dimension(myMinimunWidth, myMinimunHeigth);
    else
    return super.getMinimumSize();
    protected void paintComponent(Graphics g)
    if (getModel().getRowCount<1 && isOpaque()) { //paint background
    g.setColor(Color.white);
    g.fillRect(0, 0, getWidth(), getHeight());
    else super.paintComponent(g);
    }

  • Random slowdown of BufferedImage painting.

    Relying on another thread that dealed with painting background image in GUI using Borders, I wrote a custom Border that display an image in the background. This is quite smart and stylish, it works and looks beautifull, except that.....
    I get sometimes a slowdown (on specific images) in painting. I mean : if I resize the window that contain the JPanel with my "ImageBorder", or if I hide then re-make visible this window, with a lot of images it is cool but with some specific images (always the same files) is take 100% CPU for 3 to 10s.
    It is not size-dependant as I suspected, cause somme huge images repaint quick as some small ones repaint slow qith 100% CPU.
    It is not type-dependant (TYPE_INT_XXX or TYPE_BYTE_YYY or other) as I thought... I believed first that images with Alpha-channel where slower but is it false : huges TYPE_CUSTOM png images with alpha channel repaint faster than a specific TYPE_3BYTE_BGR small jpeg image...
    So is there a bug in J2SE 1.4 (I'm using Hotspot 1.4.1-b21, mixed mode) ?
    Or is my code wrong ? Is it possible to predict wich images will slow down painting process ?
    package jro.gui.border;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.awt.image.BufferedImageOp;
    import javax.imageio.ImageIO;
    import javax.swing.border.Border;
    * A border with a background image for GUI enhancement...
    * @author Kilwch
    public class ImageBorder implements Border {
         private BufferedImage aImage;
         private ImageBorder(){
         public ImageBorder(BufferedImage backgroundImage){
              aImage=backgroundImage;
         /* (non-Javadoc)
          * @see javax.swing.border.Border#isBorderOpaque()
         public boolean isBorderOpaque() {
              //TODO : utiliser la transparence de l'image pour d�terminer si opaque ou non
              return true;
         /* (non-Javadoc)
          * @see javax.swing.border.Border#paintBorder(java.awt.Component, java.awt.Graphics, int, int, int, int)
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
              if(g instanceof Graphics2D){
                   Graphics2D g2d=(Graphics2D)g;
                   int w=aImage.getWidth(), h=aImage.getHeight();
                   if(w!=width || h!=height){
                        BufferedImageOp op=new AffineTransformOp(AffineTransform.getScaleInstance(width/(double)aImage.getWidth(),height/(double)aImage.getHeight()),AffineTransformOp.TYPE_BILINEAR);
                        //TODO PROBLEM Draw with scale op is high-CPU consuming  ! Due to Alpha channel ? Problem occured with QNS only
                        g2d.drawImage(aImage, op, x, y);
                   }else
                        g2d.drawImage(aImage, null, x, y);
         /* (non-Javadoc)
          * @see javax.swing.border.Border#getBorderInsets(java.awt.Component)
         public Insets getBorderInsets(Component c) {
              return new Insets(0,0,0,0);//Copie d�fensive, car Insets a des attributs publics ! grr...
         public static void main(String[] args) {
              if(args.length<1){
                   System.err.println("Missing argument : image URL/path");
                   System.exit(0x80010000);
              java.net.URL imageURL=ImageBorder.class.getClassLoader().getResource(args[0]);
              if(imageURL==null){
                   System.err.println("Invalid image URL/path : "+args[0]);
                   System.exit(0x80020000);
              BufferedImage img;
              try{
                   img=ImageIO.read(imageURL);
                   StringBuffer imgMsg=new StringBuffer(256);
                   imgMsg.append("Image loaded: ").append(imageURL).append("\n * type = ");
                   switch(img.getType()){
                        case BufferedImage.TYPE_3BYTE_BGR: imgMsg.append("TYPE_3BYTE_BGR"); break;
                        case BufferedImage.TYPE_4BYTE_ABGR: imgMsg.append("TYPE_4BYTE_ABGR"); break;
                        case BufferedImage.TYPE_4BYTE_ABGR_PRE: imgMsg.append("TYPE_4BYTE_ABGR_PRE"); break;
                        case BufferedImage.TYPE_BYTE_BINARY: imgMsg.append("TYPE_BYTE_BINARY"); break;
                        case BufferedImage.TYPE_BYTE_GRAY: imgMsg.append("TYPE_BYTE_GRAY"); break;
                        case BufferedImage.TYPE_BYTE_INDEXED: imgMsg.append("TYPE_BYTE_INDEXED"); break;
                        case BufferedImage.TYPE_CUSTOM: imgMsg.append("TYPE_CUSTOM"); break;
                        case BufferedImage.TYPE_INT_ARGB: imgMsg.append("TYPE_INT_ARGB"); break;
                        case BufferedImage.TYPE_INT_ARGB_PRE: imgMsg.append("TYPE_INT_ARGB_PRE"); break;
                        case BufferedImage.TYPE_INT_BGR: imgMsg.append("TYPE_INT_BGR"); break;
                        case BufferedImage.TYPE_INT_RGB: imgMsg.append("TYPE_INT_RGB"); break;
                        case BufferedImage.TYPE_USHORT_555_RGB: imgMsg.append("TYPE_USHORT_555_RGB"); break;
                        case BufferedImage.TYPE_USHORT_565_RGB: imgMsg.append("TYPE_USHORT_565_RGB"); break;
                        case BufferedImage.TYPE_USHORT_GRAY: imgMsg.append("TYPE_USHORT_GRAY"); break;
                        default: imgMsg.append("unknown");
                   imgMsg.append(" (type ").append(img.getType()).append(")");
                   imgMsg.append("\n * Dim = ").append(img.getWidth()).append("x").append(img.getHeight());
                   System.out.println(imgMsg);
              }catch(java.io.IOException pIOEx){
                   System.err.println(pIOEx);
                   System.exit(0x80030000);
                   img=null;//Yes, thats dead code !
              javax.swing.JFrame testFrame=new javax.swing.JFrame();
              testFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              testFrame.setTitle("Test frame for "+ImageBorder.class.getName());
              testFrame.setSize(img.getWidth(), img.getHeight());
              ((javax.swing.JPanel)testFrame.getContentPane()).setBorder(new ImageBorder(img));
              testFrame.getContentPane().setLayout(new BorderLayout());
              javax.swing.JLabel [] l={new javax.swing.JLabel(args[0]),new javax.swing.JLabel()};
              l[0].setForeground(new java.awt.Color(0x00,0x00,0x66,0xC0));
              l[0].setBackground(new java.awt.Color(0xFF,0xFF,0x99,0x30));
              l[0].setOpaque(true);
              testFrame.getContentPane().add(l[0], BorderLayout.NORTH);
              testFrame.getContentPane().add(l[1], BorderLayout.CENTER);
              testFrame.setVisible(true);
    }

    I've just tried out the VolatileImage. It is a partial workaround for my problem :
    1) the very first paint of my VolatileImage (and next "first paint after contentLost") takes bloody ages, because I need to create a BufferedImage first (from an URL).
    2)Then, each time I need to resize my VolatileImage (because I want it to fit the JFrame's content pane), I have to recreate it, so I re-use the BufferedImage that is the source data, and it re-takes bloody ages.
    3) it is OK since the content of VolatileImage is not lost. So minimize/restore the parent JFrame does not slow down repaint anymore, hiding the parent JFrame with another window then putting it back to front does not slow repaint anymore.
    4)Big Alpha problem : The volatile image is used to paint the borders of the content pane. Imagine now your content pane contains a yellow JLabel with 75% transparency : when another window passes over the JLabel, it look ugly (the window lets dirty marks). It seems that transparent components does not refresh with the underlying image like expected.
    (Note that I know where the slowdown occurs in the paint method : it occurs during image resize (scaling with BufferedImageOp). But I repeat, only on specific images, regardless of their size&colordepth. As I always need a BufferedImage to "remember" the picture to paint on VolatileImage, the slowdown occurs less often, but still occurs)
    Test it for the 4th problem (1st and 2nd come along with specifig images only), passing an image path as 1st arg (note the path is relative to current dir or any classpath dir as I'm using getRessource method):
    package jro.gui.border;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.awt.image.BufferedImageOp;
    import java.awt.image.VolatileImage;
    import javax.imageio.ImageIO;
    import javax.swing.border.Border;
    * A border with a background image for GUI enhancement...
    * @author rousseau_j
    public class VolatileImageBorder implements Border {
         private VolatileImage aVImage;
         private BufferedImage aStaticImage;
         private VolatileImageBorder(){
         public VolatileImageBorder(BufferedImage backgroundImage){
              aStaticImage=backgroundImage;
         /* (non-Javadoc)
          * @see javax.swing.border.Border#isBorderOpaque()
         public boolean isBorderOpaque() {
              //TODO : utiliser la transparence de l'image pour d�terminer si opaque ou non
              return true;
         /* (non-Javadoc)
          * @see javax.swing.border.Border#paintBorder(java.awt.Component, java.awt.Graphics, int, int, int, int)
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
              if((g instanceof Graphics2D)&& c!=null){
                   Graphics2D g2d=(Graphics2D)g;
                   if(aVImage==null){
                        aVImage=c.createVolatileImage(width, height);
                   int w=aVImage.getWidth(), h=aVImage.getHeight();
                   if(w!=width || h!=height){
                        aVImage=c.createVolatileImage(width, height);
                   do{
                        int returnCode = aVImage.validate(c.getGraphicsConfiguration());
                        if (returnCode == VolatileImage.IMAGE_RESTORED) {
                             renderOffscreen(c, x, y, width, height);
                        } else if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
                             aVImage = c.createVolatileImage(width, height);
                             renderOffscreen(c, x, y, width, height);
                        g2d.drawImage(aVImage, 0, 0, c);
                   }while(aVImage.contentsLost());
         private void renderOffscreen(Component c, int x, int y,int width,  int height){
              System.out.print("renderOffscreen{");//TEST
              do{
                   System.out.print("do{...");//TEST
                   if(aVImage.validate(c.getGraphicsConfiguration())==VolatileImage.IMAGE_INCOMPATIBLE){
                        aVImage=c.createVolatileImage(width, height);
                   Graphics2D vImgG2d=aVImage.createGraphics();
                   int w=aStaticImage.getWidth(), h=aStaticImage.getHeight();
                   if(w!=width || h!=height){
                        //TODO : option pour une redim d�finitive si image trop grande
                        BufferedImageOp op=new AffineTransformOp(AffineTransform.getScaleInstance(width/(double)aStaticImage.getWidth(),height/(double)aStaticImage.getHeight()),AffineTransformOp.TYPE_BILINEAR);
                        //TODO PROBLEM Draw with scale op is high-CPU consuming  ! Due to Alpha channel ? Problem occured with QNS only
                        vImgG2d.drawImage(aStaticImage, op, x, y);
                   }else
                   vImgG2d.drawImage(aStaticImage, null, x, y);
                   vImgG2d.dispose();
                   System.out.print("...}while; ");//TEST
              }while(aVImage.contentsLost());
              System.out.println("}\n");//TEST
         /* (non-Javadoc)
          * @see javax.swing.border.Border#getBorderInsets(java.awt.Component)
         public Insets getBorderInsets(Component c) {
              return new Insets(0,0,0,0);//Copie d�fensive, car Insets a des attributs publics ! grr...
         public static void main(String[] args) {
              if(args.length<1){
                   System.err.println("Missing argument : image URL/path");
                   System.exit(0x80010000);
              java.net.URL imageURL=VolatileImageBorder.class.getClassLoader().getResource(args[0]);
              if(imageURL==null){
                   System.err.println("Invalid image URL/path : "+args[0]);
                   System.exit(0x80020000);
              BufferedImage img;
              try{
                   img=ImageIO.read(imageURL);
                   StringBuffer imgMsg=new StringBuffer(256);
                   imgMsg.append("Image loaded: ").append(imageURL).append("\n * type = ");
                   switch(img.getType()){
                        case BufferedImage.TYPE_3BYTE_BGR: imgMsg.append("TYPE_3BYTE_BGR"); break;
                        case BufferedImage.TYPE_4BYTE_ABGR: imgMsg.append("TYPE_4BYTE_ABGR"); break;
                        case BufferedImage.TYPE_4BYTE_ABGR_PRE: imgMsg.append("TYPE_4BYTE_ABGR_PRE"); break;
                        case BufferedImage.TYPE_BYTE_BINARY: imgMsg.append("TYPE_BYTE_BINARY"); break;
                        case BufferedImage.TYPE_BYTE_GRAY: imgMsg.append("TYPE_BYTE_GRAY"); break;
                        case BufferedImage.TYPE_BYTE_INDEXED: imgMsg.append("TYPE_BYTE_INDEXED"); break;
                        case BufferedImage.TYPE_CUSTOM: imgMsg.append("TYPE_CUSTOM"); break;
                        case BufferedImage.TYPE_INT_ARGB: imgMsg.append("TYPE_INT_ARGB"); break;
                        case BufferedImage.TYPE_INT_ARGB_PRE: imgMsg.append("TYPE_INT_ARGB_PRE"); break;
                        case BufferedImage.TYPE_INT_BGR: imgMsg.append("TYPE_INT_BGR"); break;
                        case BufferedImage.TYPE_INT_RGB: imgMsg.append("TYPE_INT_RGB"); break;
                        case BufferedImage.TYPE_USHORT_555_RGB: imgMsg.append("TYPE_USHORT_555_RGB"); break;
                        case BufferedImage.TYPE_USHORT_565_RGB: imgMsg.append("TYPE_USHORT_565_RGB"); break;
                        case BufferedImage.TYPE_USHORT_GRAY: imgMsg.append("TYPE_USHORT_GRAY"); break;
                        default: imgMsg.append("unknown");
                   imgMsg.append(" (type ").append(img.getType()).append(")");
                   imgMsg.append("\n * Dim = ").append(img.getWidth()).append("x").append(img.getHeight());
                   System.out.println(imgMsg);
              }catch(java.io.IOException pIOEx){
                   System.err.println(pIOEx);
                   System.exit(0x80030000);
                   img=null;//Yes, thats dead code !
              javax.swing.JFrame testFrame=new javax.swing.JFrame();
              testFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              testFrame.setTitle("Test frame for "+VolatileImageBorder.class.getName());
              testFrame.setSize(img.getWidth(), img.getHeight());
              ((javax.swing.JPanel)testFrame.getContentPane()).setBorder(new VolatileImageBorder(img));
              testFrame.getContentPane().setLayout(new BorderLayout());
              javax.swing.JLabel [] l={new javax.swing.JLabel(args[0]),new javax.swing.JLabel()};
              l[0].setForeground(new java.awt.Color(0x00,0x00,0x66,0xC0));
              l[0].setBackground(new java.awt.Color(0xFF,0xFF,0x99,0x30));
              l[0].setOpaque(true);
              testFrame.getContentPane().add(l[0], BorderLayout.NORTH);
              testFrame.getContentPane().add(l[1], BorderLayout.CENTER);
              testFrame.setVisible(true);
    }

  • How to wait until all components painted?

    Hi - I have searched for hours for an answer to this and have yet to find something so any help is much appreciated!
    Ive posted some code below to simulate the problem im facing. This is a simple frame which has a couple of custom jPanels embedded within it.
    When this is run, the first 3 lines i see are:         I want this comment to be the last thing output
            Now finished panel paint
            Now finished panel paintBut, as this output suggests, i want the "I want this comment to be the last thing output" line to be displayed after the two panels are completely painted on the screen (in real life i need to know my components are displayed before the program can move on to further processing). Of course, if you cause a repaint you see the "now finished panel paint" each time, but im not interested in this, im simply interested in how to overcome this when the frame is first created and shown.
    Ive tried everything i can think of at the "// ***** What do i need to put here? ******" position but nothing seems to work... In short my question is how can i construct my frame and get it to ensure that all components are fully displayed before moving on?
    Sorry if the answer to this is obvious to someone who knows these things, but its driving me mad.
    Cheers
    import javax.swing.*;
    import java.awt.*;
    public class Frame1 extends JFrame {
      public static void main(String[] args) {
        Frame1 frame1 = new Frame1();
        // ***** What do i need to put here? ******
        // to ensure that the System.err.. call below
        // is only executed once both panels paint methods
        // have finished?????
        System.err.println("I want this comment to be the last thing output");
        System.err.flush();
      public Frame1() {
        this.getContentPane().setLayout(new FlowLayout());
        MyPanel  p1 = new MyPanel(); p1.setBackground(Color.red);
        MyPanel  p2 = new MyPanel(); p2.setBackground(Color.green);
        this.getContentPane().add(p1, null);
        this.getContentPane().add(p2, null);
        this.pack();
        this.setVisible(true);
      class MyPanel extends JPanel {
        Dimension preferredSize = new Dimension(200,200);
        public Dimension getPreferredSize() { return preferredSize;  }
        public MyPanel () { }
        public synchronized void paintComponent(Graphics g) {
          super.paintComponent(g);  //paint background
          // do some irrelevant drawing to simulate a bit of work...
          for (int i=0; i<200; i+=20) {
            g.drawString("help please!",50,i);
          System.err.println("Now finished panel paint"); System.err.flush();
        } // end of MyPanel
      }

    Thanks both for your replies.
    When doing the "Runnable runnable = new Runnable(){public void run(){ frame1.paint(frame1.getGraphics());....." method i sometimes see
        Now finished panel paint
        Now finished panel paint
        I want this comment to be the last thing output       
        Now finished panel paint
        Now finished panel paintwhich is a pain.
    As for making a new Runnable to do the system.err.println and then doing the SwingUtilities(invoke) on that runnable, that didnt work for me at all.
    So... in the end, my solution was to have the paint method set a boolean when finished and the main program sleep while this is false
         // Dont want to sleep for say a few seconds as cant be sure
         //painting will be finished, must monitor state of painting ...
         //therefore use while loop
         while (!isOk) {  // isOk is true when both panel paint methods complete
             System.err.println("Waiting......");
             try{   Thread.sleep(300 /* wait some time */);  }
             catch(Exception e){}
           System.err.println("Thankfully this works");which is a kind of mixture of both your suggestions i guess!
    Thanks for your help, much appreciated.

  • Can I make IE 6 to display a transparent background?

    I have a sidebar that has a hand painted background. On this
    background I have buttons with writing. These buttons are .png with
    a transparent background. In every browser that I tested the
    background of the button remains transparent and blends nicely with
    the hand painted background. However, in IE6 the background does
    not remain transparent and there is an ugly edge around the button
    instead of the transparency. Is there any way to modify this with a
    CSS rule? IE6 can be such a pain.
    Lou

    See recent post CSS Opacity
    From Blue_Vision
    Dave
    "louhosta" <[email protected]> wrote in
    message
    news:gobrgm$ckk$[email protected]..
    > I have a sidebar that has a hand painted background. On
    this background I
    have
    > buttons with writing. These buttons are .png with a
    transparent
    background. In
    > every browser that I tested the background of the button
    remains
    transparent
    > and blends nicely with the hand painted background.
    However, in IE6 the
    > background does not remain transparent and there is an
    ugly edge around
    the
    > button instead of the transparency. Is there any way to
    modify this with a
    CSS
    > rule? IE6 can be such a pain.
    > Lou
    >

  • Display a background image

    I want to display an image into a panel and then add this panel to a frame. I used the following code but I don't know why the image doesn't appear.
    Test.java :
    public class Test {
    private JFrame framePrincipal;
    private JPanel panel;
    private Toolkit toolkit = Toolkit.getDefaultToolkit();
    private Image image = toolkit.getImage ("C:/ProGolf/Images/image.jpg");
    public Test (){
         panel = new JPanel();
         framePrincipal=new JFrame("Club de Golf Joliette");
         framePrincipal.setBackground(new Color(185,211,238));
         ImagePanel imagePanel = new ImagePanel(image);
         panel.add(imagePanel,BorderLayout.CENTER);
         framePrincipal.setContentPane(panel);
         framePrincipal.setSize(new Dimension(650,200));
         framePrincipal.setVisible(true);
    public static void main (String [] args){
         Test monTest = new Test();
    ImagePanel.java :
    public class ImagePanel extends JPanel {
    Image image;
    public ImagePanel(Image image) {
    this.image = image;
    public void paintComponent(Graphics g) {
    super.paintComponent(g); //paint background
    //Draw image at its natural size first.
    g.drawImage(image, 0, 0, this); //85x62 image

    Simpler than that;-import java.awt.*;
    import javax.swing.*;
    public class JFrameImage extends JFrame {
      public JFrameImage() {
          super("Images on a JFrame");
          Container c    = getContentPane();
          JPanel panel = new JPanel(){
                 public void paintComponent(Graphics g)     {
                      ImageIcon img = new ImageIcon("myImg.jpg");
                      g.drawImage(img.getImage(), 0, 0, null);
                      super.paintComponent(g);
            panel.setOpaque(false);
          c.add(panel);
      public static void main(String[] args) {
        JFrameImage frame = new JFrameImage();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.setVisible(true);
    // and here we have stretch to fit too!
          JPanel panel = new JPanel(){
                 public void paintComponent(Graphics g)     {
                      ImageIcon img = new ImageIcon("myImg.jpg");
                ImageIcon bigImage = new ImageIcon(img.getImage().getScaledInstance
                                   (getWidth(), getHeight(),Image.SCALE_REPLICATE));
                g.drawImage(bigImage.getImage(), 0, 0, this);
                      super.paintComponent(g);
            panel.setOpaque(false);
    // and finally tiling
             JPanel panel = new JPanel(){
                    public void paintComponent(Graphics g)     {
                      ImageIcon img = new ImageIcon("smallImage.jpg");
                int x = img.getImage().getWidth(this);
                int y = img.getImage().getHeight(this);
                   for (int tileY = 0; tileY < getWidth(); tileY += y)
                   for (int tileX = 0; tileX < getHeight();tileX += x)
                   g.drawImage(img.getImage(), tileX, tileY, this);    
                       super.paintComponent(g);
            panel.setOpaque(false);

  • Problems with painting

    I am trying to put jlabel(with a picture ) on another jlabel (with a picture) how i could do this... oh i am using ide interface, when i put one on another it always goes near by it but not on it! pls help me! ;)
    tryed many things as painting background then moving on it label but there comes grey color(bakcground color) after moving to another place.
    repaint overloads system or smth like this. well i a can say i am going to panic now :(
    sorry for spaming in many forums but i really need help:(

    audryste wrote:
    sorry for spaming in many forums but i really need help:(Choose one thread and state in the other that it is closed or you will severely limit the help folks will offer you.

  • Image as a background for a JFrame

    Hi all,
    Is it possible to have an image as a background for a JFrame?
    How do you do it?
    plz help

    i personally inherit a panel...
      class ImagePanel extends JPanel {
          Image image;
          public ImagePanel(Image image) {
              this.image = image;
          public void paintComponent(Graphics g) {
              super.paintComponent(g); //paint background
              //Draw image at its natural size first.
              g.drawImage(image, 0, 0, this); //85x62 image
      } and call it with
      private Image icLogo =
    Toolkit.getDefaultToolkit().getImage(getClass().getResource("icLogo.gif"));
      private JPanel imgPanel = new ImagePanel(icLogo);Well, this should work with frames, too. In case it doesn't, you can simply add this panel to the frame.
    greets
    Jochen

  • Container panels transparent in JInternalFrame with Windows XP Style

    Hi All
    I have a problem with a GUI where panels extending java.awt.Container (added to JInternalFrame) are transparent when using Windows XP Style (Windows XP Pro). The components added to the Container (for example JButton, JComboBox etc.) paint correctly but the surrounding space of the Container to which they belong is translucent such that the desktop below can be seen.
    When I switch to Windows Classic Style this does not happen. I'm using JDK6.0.
    Has anyone encountered this problem?
    Help appreciated
    Lance

    Just an update; this is the config I'm using to bootstrap the app (in main):
      UIManager.put("swing.boldMetal", Boolean.FALSE);
      UIManager.put("ToolTip.background", Color.YELLOW);
      JDialog.setDefaultLookAndFeelDecorated(true);
      JFrame.setDefaultLookAndFeelDecorated(true);
      Toolkit.getDefaultToolkit().setDynamicLayout(true);
      System.setProperty("sun.awt.noerasebackground","true");
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());The GUI is assembled from basic panels which extend Container, typical example below:
    public class BottomContainer extends Container implements ActionListener {
         private ActionListener handler;
         private ModeButton closeCancelButton;
         private JProgressBar progressBar;
         private ResourceBundle bundle;
         public BasicBottomContainer(ResourceBundle bundle) {
              super();
              this.bundle = bundle;
              createGui();
         public void actionPerformed(ActionEvent e) {
              Object source = e.getSource();
              ActionEvent xEvent = null; // translated event
              if (source == closeCancelButton) {
                   ButtonModes mode = ((ModeButton) source).getMode();
                   if (mode == ButtonModes.CANCEL) {
                        xEvent = new ProxyActionEvent(ActionProxies.CANCEL_BUTTON);
                   } else if (mode == ButtonModes.CLOSE) {
                        xEvent = new ProxyActionEvent(ActionProxies.CLOSE_BUTTON);
                   } else {
                        throw new IllegalArgumentException("Mode not defined");
              } else {
                   throw new IllegalArgumentException("Source not defined");
              handler.actionPerformed(xEvent);
         private void createGui() {
              setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
              progressBar = new JProgressBar();
              progressBar.setMinimum(0);
              progressBar.setMaximum(100);
              progressBar.setVisible(false);
              JPanel progressPanel = new JPanel();
              progressPanel.setLayout(new BorderLayout());
              progressPanel.add(progressBar, BorderLayout.CENTER);
              GuiUtils.setFixedSize(progressPanel, 200, 13);
              progressPanel.setVisible(false);
              ButtonModes mode = ButtonModes.CLOSE;
              closeCancelButton = new ModeButton(bundle.getString("closeButton"), mode);
              localeChangeList.add(closeCancelButton, "closeButton");
              closeCancelButton.setMinimumSize(new Dimension(80, 25));
              closeCancelButton.addActionListener(this);
              add(GuiUtils.rigidArea(15, 55)); // spacing with left-hand border & height
              add(progressPanel);
              add(Box.createHorizontalGlue()); // push apart
              add(closeCancelButton);
              add(GuiUtils.rigidArea(15, 0)); // spacing with right-hand border
              setVisible(false);
         public void updateRefreshProgress(int refreshProgress) {
              progressBar.setValue(refreshProgress);
         public void setCloseCancelButtonMode(ButtonModes mode) {
              closeCancelButton.setMode(mode);
         public void setHandler(ActionListener handler) {
              this.handler = handler;
    }The Container above is then attached in the main GUI something like this:
    public abstract class TestView extends AbstractView {
         protected TopContainer topContainer;
         protected MiddleContainer middleContainer;
         protected BottomContainer bottomContainer;
         public AbstractView() {
              createGui();
         private void createGui() {
              topContainer = new TopContainer(model.getBundle());
              middleContainer = new MiddleContainer();
              bottomContainer = new BottomContainer(model.getBundle());
              infoPanel.setVisible(false);
              container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
              container.add((Container) topContainer);
              container.add((Container) middleContainer);
              container.add(infoPanel.getContainer());
              container.add((Container) bottomContainer);
         protected void dispose() {
              super.dispose();
         public final void showGui(boolean visible) {
              super.showGui(visible);
              topContainer.setVisible(true);
              middleContainer.setVisible(true);
              bottomContainer.setVisible(true);
    }It appears that all the components (e.g. BottomContainer, TopContainer etc)
    which extend Container are transparent but I'm not able to replicate it with a simpler class (the panels are always opaque in simpler setup).
    Has anyone seen this before (as I mentioned above, this only happens when I set my config for Windows XP Pro to 'Windows XP Style' in the Control Panel).
    Help much appreciated
    Lance

  • How can I make a tabbed pane transparent ?

    I have a tabbed pane placed on a JPanel with an image background. I added a tabbed pane with tabbedPane.setOpaque (false), however I still can't see the image behind the components that were added as tabs in the tabbedpane. Any help will be greatly appreciated.
    Here's a simplified version of the code:
    public class Example extends JPanel {
         public Example() {
              tabs = new JTabbedPane();
              tabs.setOpaque (false);
              JPanel tp1 = new JPanel();
              tp1.setOpaque(false);
              tabs.addTab ("panel 1", tp1);
              this.add (tabs);
         public void paintComponent(Graphics g) {
              // Paint background image
              g.drawImage(...);
    }

    Perhaps the opaque property is internally overset by the tab pane.
    Try this:
       public class Example extends JPanel {
          public Example() {
             JTabbedPane tabs = new JTabbedPane() {
                public boolean isOpaque() {
                   return false;
             JPanel tp1 = new JPanel() {
                public boolean isOpaque() {
                   return false;
             tabs.addTab("panel 1", tp1);
             this.add (tabs);
          public void paintComponent(Graphics g) {
             // Paint background image
             g.drawImage(...);
       } Regards.

  • How can I update my image in a loop?

    I want to use "paint( )" automaticlly to display my 3D image slice by slice. I can't understand why it only display my final slice. Below is my coeds:
    // press butten to display my 3D image slice by slice
    if(e.getActionCommand() == "Play")
         for(int i = 0; i < finalSlice; i++)
              if(presentSlice == finalSlice)
                   presentSlice = 0;
              presentSlice = presentSlice + 1;
              // read a new slice from a 3D data. Return
              // matrix is a new 2D image data
              pixel = mccd.readSlice(presentSlice, mapModel);
              //Gererate a new slice image
              img = createImage(new MemoryImageSource(width, height, pixel, 0, width));
              //input the image onto my image panel;
              imgPanel.imageUpdate(img);
              } // Here can not work. Only can               // work in the last time of loop.
    public class ImagePanel extends JPanel
         public void imageUpdate(Image image)
              this.image = image;
              repaint();
         public void paintComponent(Graphics g)
              super.paintComponent(g); //paint background
              //Draw image at its natural size first.
              g.drawImage(image, 0, 0, this);
    Thanks a lot for any help. Could you email me on
    [email protected] Thanks again

    You can try the following:
    Create a new object that extends runnable. Have a variable that keeps track of the current slice. In its paint() method, paint the current slice.
    Now, in its run() method start from the first slice and get into a loop that calls Thread.sleep(1000) and then makes the current slice = to the next slice. you can replace 1000 with whatever duration you want.
    My recommendation is that this object should extend a container. After that, you just add the component into a window and display it.
    Hope this helps,
    Calin
    PS: I did this and it worked for me. If you need it I will try to give you some code you can start from.

  • How to put graphics into a JViewport?

    Hi,
    I'm trying to make a simple game, where a block can move around in a 30x30 grid with collision detection. So far, it works alright, but I want the window to hold only 10x10 and for the block that is moving to stay at the center while the painted background moves around. The program reads a .dat file to get the world.
    So is there a way to use the background world Ive painted and put it into a viewport so that it will scroll when the keys are hit to move? Also I'd like to make the block stay at the center of the screen, unless it's at a corner.
    Hopefully this makes sense and someone can help. Thanks.
    Here's my code:
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.io.*;
    public class SmallWorld extends JPanel
                              implements KeyListener,
                                         ActionListener {
         //WORLD
         String[][] worldArray = new String[30][30];
         private static Color redBlock = new Color(255,0,0,255);
         private static Color whiteBlock = new Color(255,255,255,150);
         private static Color blackBlock = new Color(0,0,0,150);
         boolean keyUP = false;
         boolean keyDOWN = false;
         boolean keyLEFT = false;
         boolean keyRIGHT = false;
         //Starting coordinates
         int blockPositionX = 1;
         int blockPositionY = 1;
         JTextField typingArea;
         JViewport viewable;
        public SmallWorld() {
            super( );
              createWorld();     
            typingArea = new JTextField(20);
            typingArea.addKeyListener(this);
              typingArea.setEditable( false );
              add(typingArea);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              String type = "";
              for (int i = 0; i < 30; i++) {
                   for (int j = 0; j < 30; j++) {
                        type = worldArray[i][j];
                             if ( type.equals("1") )
                                  g.setColor(redBlock);
                                  g.fillRect( (j * 50),(i * 50),50,50 );
                             else {
                                  g.setColor(whiteBlock);
                                  g.fillRect( (j * 50),(i * 50),50,50 );          
              g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );     
         //Get the world from the DAT file and translate it into a 2d array to be used by paintComponent
         public void createWorld() {
            String getData = null;
              int countRow = 0;
            try {
                   FileReader fr = new FileReader("world.dat");
                   BufferedReader br = new BufferedReader(fr);
                   getData = new String();
                   while ((getData = br.readLine()) != null) {
                  if(countRow < 30) {
                        for (int i = 0; i < 30; i++) {
                             String temp = "" + getData.charAt(i);
                             worldArray[countRow] = temp;
                        countRow++;
    } catch (IOException e) {
    // catch possible io errors from readLine()
    System.out.println("Uh oh, got an IOException error!");
    e.printStackTrace();
         //Move Block around the world
         public void moveBlock() {
              Graphics g = this.getGraphics();
              Point pt = new Point();
              pt.x = blockPositionX * 50;
              pt.y = blockPositionY * 50;
              if (keyUP) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
              if (keyDOWN) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
              if (keyLEFT) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
              if (keyRIGHT) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
         //check for collisions with blocks
         public boolean checkCollision(int row, int col) {
              if ( worldArray[col][row].equals("1") ) {
                   return true;
              else {
                   return false;
    //If key typed, put action here. none for now
    public void keyTyped(KeyEvent e) {
    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
    updateView( e );
    //If key released, put action here. none for now
    public void keyReleased(KeyEvent e) {
    /** Handle the button click. */
    public void actionPerformed(ActionEvent e) {
         //Update the view of the window based on which button is pressed
         protected void updateView( KeyEvent e ) {
              //if UP is pressed
              if ( e.getKeyCode() == 38 ) {
                   keyUP = true;
                   if ( checkCollision( blockPositionX, blockPositionY - 1 ) == false ) {
                        blockPositionY = blockPositionY - 1;
                        this.repaint();
                        moveBlock();
                   keyUP = false;
              //if DOWN is pressed
              if ( e.getKeyCode() == 40 ) {
                   keyDOWN = true;
                   if ( checkCollision( blockPositionX, blockPositionY + 1 ) == false ) {
                        blockPositionY = blockPositionY + 1;
                        this.repaint();
                        moveBlock();
                   keyDOWN = false;
              //if LEFT is pressed
              if ( e.getKeyCode() == 37 ) {
                   keyLEFT = true;
                   if ( checkCollision( blockPositionX - 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX - 1;
                        this.repaint();
                        moveBlock();
                   keyLEFT = false;
              //if RIGHT is pressed
              if ( e.getKeyCode() == 39 ) {
                   keyRIGHT = true;
                   if ( checkCollision( blockPositionX + 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX + 1;
                        this.repaint();
                        moveBlock();
                   keyRIGHT = false;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("SmallWorld");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new SmallWorld();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
         frame.setSize(500,520);
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    The world DAT file:
    111111111111111111111111111111
    100010001010001000101000100011
    100010001010001000101000100011
    100011101010000000001000000001
    100010000010000000001000000001
    100110000010000000001000000001
    100000000010000000001000000001
    111100011110000000001000000001
    100000000110001110111000111011
    100000000000001110111000111011
    100000000000000000001000000001
    100010001110000000000000000001
    100010001110001110111000111011
    100011101100000000000000000011
    100010000110001110111000111011
    100110000100000000000000000011
    100000000110000000001000000001
    111100011100000000000000000011
    100000000100000000000000000011
    100000000010000000000000000001
    100000000010000000000000000001
    100010000000000000000000000001
    100010000000001110111000111011
    100011101110000000011000000001
    100010000110000000011000000001
    100110000110000000001000000001
    100000000110001110111000111011
    111100011110000000011000000001
    100000000110000000011000000001
    100000000011111111111111111111

    I know this is an old posting, but I just saw another question similiar to this and I still have my old code lying around that incorporates most of the suggestions made in this posting. So I thought I'd post my code here in case anybody wants to copy/paste the code. You will still need to use the DAT file provide above as well as provide icons to represent the floor and wall.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class SmallWorld extends JPanel implements KeyListener, ActionListener
         //WORLD
         String[][] worldArray = new String[30][30];
         //Block colors
         private static Color redBlock = new Color(255,0,0,255);
         private static Color whiteBlock = new Color(255,255,255,255);
         private static Color blackBlock = new Color(0,0,0,150);
         //World images
    //     JLabel wall = new JLabel( new ImageIcon("wall.gif") );
    //     JLabel floor = new JLabel( new ImageIcon("floor.gif") );
         ImageIcon wallIcon = new ImageIcon("dukewavered.gif");
         ImageIcon floorIcon = new ImageIcon("copy16.gif");
         //Starting coordinates
         int blockPositionX = 1;
         int blockPositionY = 1;
         //Typing area to capture keyEvent
         JTextField typingArea;
         //Viewable area
         JViewport viewable;
         String type = "";
         JLayeredPane layeredPane;
         JPanel worldBack;
         JPanel panel;
         JPanel player;
         Dimension worldSize = new Dimension(1500, 1500);
         public SmallWorld() {
              super( );
              createWorld();
              layeredPane = new JLayeredPane();
              add(layeredPane);
              layeredPane.setPreferredSize( worldSize );
              worldBack = new JPanel();
              layeredPane.add(worldBack, JLayeredPane.DEFAULT_LAYER);
              worldBack.setLayout( new GridLayout(30, 30) );
              worldBack.setPreferredSize( worldSize );
              worldBack.setBounds(0, 0, worldSize.width, worldSize.height);
              worldBack.setBackground( whiteBlock );
              for (int i = 0; i < 30; i++) {
                   for (int j = 0; j < 30; j++) {
                        JPanel square = new JPanel( new BorderLayout() );
                        worldBack.add( square );
                        type = worldArray[i][j];
                        if ( type.equals("1") )
                             square.add( new JLabel(wallIcon) );
                        else
                             square.add( new JLabel(floorIcon) );
              //Draw the player
              player = new JPanel();
              player.setBounds(50, 50, 50, 50);
              player.setBackground( Color.black );
              player.setLocation(50, 50);
              layeredPane.add(player, JLayeredPane.DRAG_LAYER);
              //set where the player starts
    //          panel = (JPanel)worldBack.getComponent( 31 );
    //          panel.add( player );
              //Create the typing area with keyListener, add to window
              typingArea = new JTextField(20);
              typingArea.addKeyListener(this);
              typingArea.setEditable( false );
              add(typingArea);
         //Get the world from the DAT file and translate it into
         //a 2d array to be used by paintComponent
         public void createWorld() {
              String getData = null;
              int countRow = 0;
              try {
                   //Get file
                   FileReader fr = new FileReader("world.dat");
                   BufferedReader br = new BufferedReader(fr);
                   getData = new String();
                   //read each line from file, store to 2d array
                   while ((getData = br.readLine()) != null) {
                        if(countRow < 30) {
                             for (int i = 0; i < 30; i++) {
                                  String temp = "" + getData.charAt(i);
                                  worldArray[countRow] = temp;
                        countRow++;
              } catch (IOException e) {
              System.out.println("Uh oh, got an IOException error!");
              e.printStackTrace();
         //Move Block around the world
         public void moveBlock() {
              Point pt = new Point();
              pt.x = blockPositionX * 50;
              pt.y = blockPositionY * 50;
              int x = Math.max(0, pt.x - 250);
              int y = Math.max(0, pt.y - 250);
              Rectangle r = new Rectangle(x, y, 550, 550);
              scrollRectToVisible( r );
         //check for collisions with blocks
         public boolean checkCollision(int row, int col) {
              if ( worldArray[col][row].equals("1") ) {
                   return true;
              else {
                   return false;
         public void keyTyped(KeyEvent e) {
         public void keyPressed(KeyEvent e) {
              updateView( e );
              e.consume();
         public void keyReleased(KeyEvent e) {
         public void actionPerformed(ActionEvent e) {
         //Update the view of the window based on which button is pressed
         protected void updateView( KeyEvent e ) {
              //if UP
              if ( e.getKeyCode() == 38 ) {
                   if ( checkCollision( blockPositionX, blockPositionY - 1 ) == false ) {
                        blockPositionY = blockPositionY - 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
              //if DOWN
              if ( e.getKeyCode() == 40 ) {
                   if ( checkCollision( blockPositionX, blockPositionY + 1 ) == false ) {
                        blockPositionY = blockPositionY + 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
              //if LEFT
              if ( e.getKeyCode() == 37 ) {
                   if ( checkCollision( blockPositionX - 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX - 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
              //if RIGHT
              if ( e.getKeyCode() == 39 ) {
                   if ( checkCollision( blockPositionX + 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX + 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
         private static void createAndShowGUI() {
              JFrame frame = new JFrame("SmallWorld");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JComponent newContentPane = new SmallWorld();
              newContentPane.setPreferredSize( new Dimension(1500, 1500) );
              JScrollPane scrollPane = new JScrollPane( newContentPane );
              scrollPane.setPreferredSize( new Dimension(568, 568) );
              frame.getContentPane().add( scrollPane );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setResizable( false );
              //frame.setSize(500,520);
              frame.setVisible( true );
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater( new Runnable() {
                   public void run() {
                        createAndShowGUI();

Maybe you are looking for

  • Error while running Helloworld page from Jdeveloper

    Hi I am getting the following error while running HelloworldPG.xml from Jdeveloper. Any help in this will be greatly appreciated .. Error Page Exception Details. oracle.apps.fnd.framework.OAException: Application: FND, Message Name: FND_GENERIC_MESSA

  • Seagate Plug and Play from Macbook Pro to Macbook Air

    Recently bought a new Macbook Air to upgrade my 2010 Macbook Pro 13 inch. I had been using a Seagate Plug and Play external hardrive that needed no formatting on my Macbook Pro . However when I tried to use the same on my Macbook Air it did not allow

  • Safari Refuses To Work on Windows XP SP 3

    Hi, Just to let you know, I'm new here . I downloaded Safari a while back, but it crashed within ten minutes of using it. Now, it won't start at all and comes up with an error message, asking me to send an error report to Microsoft. Now, I've tried a

  • Batch Tables Details Required

    Hi Team, Can you please provide me the table names where i can see the quantity against the batches in the goods movement? I checked with MCHB but i couldn't get the details for all the goods movement. This particular table is updating only when the

  • XI performance issue

    Hello , I am facing one XI performance issue. We are using PI 7.1 SP 7 on AIX 5.3 and Oracle 10.2.0.4 I have testing a simple file to file scenario, every 0.09 second, PI pull one 1kb size file from AIX file system and process, PI works fine, the ite