Panel margin and alignment

Hi,
I would like all components in my (for example), JWindow to be COMPLETELY left and top aligned. How can I do this?

Thanks in advance,
-R
rubberdiAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
JohnnyAffaConnect With a Mentor Commented:
in this example, there are 3 jpanels with each one 50 pixels smaller than its parent jpanel.  as requested, each panel is bounded to the top left hand corner.  this is achieved by setting each parent jpanel's layout to null.  given your requirement, to must override the class paint method as well as call its paintComponents method.

hope its what you were after ;-)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Spacing extends JFrame
{
      JPanel panel[] = new JPanel[3];

      public Spacing()
      {
            this.setInterface();
      }

      private void setInterface()
      {
            this.setBounds(50,80,400,400);

            Container contentPane = this.getContentPane();

            panel[0] = new JPanel(null);
            panel[0].setBackground(Color.red);

            panel[1] = new JPanel(null);
            panel[1].setBackground(Color.blue);

            panel[0].add(panel[1]);

            panel[2] = new JPanel();
            panel[2].setBackground(Color.yellow);

            panel[1].add(panel[2]);

            contentPane.add(panel[0]);

            this.setVisible(true);
      }

      public void paint(Graphics g)
      {
            panel[1].setBounds(0,0,panel[0].getSize().width - 50,panel[0].getSize().height - 50);
            panel[2].setBounds(0,0,panel[1].getSize().width - 50,panel[1].getSize().height - 50);

            this.paintComponents(g);
      }

      public void processWindowEvent(WindowEvent event)
      {
            if ( event.getID() == WindowEvent.WINDOW_CLOSING )
                  System.exit(0);
      }

      public static void main(String args[])
      {
            new Spacing();
      }
}
0
 
sciuriwareCommented:
There's a lot you can do (borders, colours, fonts ...) but I can't find an alignment parameter in the
UiManager properties.
If it can be done, it should be done by calls like:

               UIManager.put("Button.font", MyFont);

;JOOP!
0
 
DrWarezzCommented:
Thanks sciuriware..
Well, an alternative (and something more conveniant would be to be able to set the background of (for example) a JWindow to an image.
I know how to change the background colour, but, can I apply an image??

Thanks :-)
-R
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
sciuriwareCommented:
I found this older solution by 'gkern':

"u can use a background panel:"

class BackgroundPanel extends JPanel
{
  protected Image bgImage = <an image>;

  public BackgroundPanel()
  {
    super(true);
    this.setLayout(new BorderLayout());
    setOpaque(false);
  }

  public void paint(Graphics gr)
  {
    gr.drawImage(bgImage, 0 ,0 ,this);
    super.paint(gr);
  }
} // BackgroundPanel

put this panel on your JFrame and place all other components on this panel instead on the JFrame content pane:
...JPanel backPanel = new BackgroundPanel();
this.getContentPane().add(backPanel);
...

It was accepted then, I think it should work.

;JOOP!
0
 
rubberdiAuthor Commented:
Hi, thanks sciuriware.
I just need a little help :o)

For this line:
protected Image bgImage = <an image>;

How do I declare the image? What do I replace the '<an image>' with?? :o\

thanks,
-R
0
 
sciuriwareConnect With a Mentor Commented:
I always use      ImageIcon
because loading it from file or .jar is synchronised (return == done completely).

How do you load an image (resource), well, I cut this from one of my applications:

   /**
    * Safely get the path to a resource file via Class info.
    * <p>If the file is missing, assuming that the resource was an image file,<BR>
    * the packaged <b>MISSING.gif</b> icon is substituted,
    * using the class info <b>packageClass</b> retrieved elsewhere.</p>
    * @param  classinfo   a Class loaded from the root of relative pathname.
    * @param  filename    the relative pathname to the resource file.
    * @return             an URL to the resulting resource.
    */
   private static URL findResource(Class classInfo, String filename)
   {
   URL resourceURL;

      if(classInfo == null)
      {
         fatal("BAD CLASS INFO");
      }

      if((resourceURL = classInfo.getResource(filename)) == null)
      {
         error("RESOURCE FILE '" + filename + "' MISSING.");
         if((resourceURL
            = packageClass.getResource("res/MISSING.gif")) == null)
         {
            fatal("SUBSTITUTE IMAGE 'MISSING' NOT FOUND.");
         }
      }
      return(resourceURL);
   }


// And deploying this in my program elsewhere (assume JFrame mainFrame;   ):

   /**
    * Set the default icon on the program main JFrame.
    * <p>Can be used to reset the icon after calls with an argument.<BR>
    * The default icon should be <b>res/<program>.gif</b>.</p>
    */
   public static void setMainFrameIcon( )
   {
      mainFrame.setIconImage
      (
         Toolkit.getDefaultToolkit().getImage(findResource(this.getClass( ), "res/Application.gif"))
      );
   }

;JOOP!
0
 
rubberdiAuthor Commented:
Thanks.
I still need further help though :o\.

I've created this (to test the code you've given):


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

public class PaneImage extends JFrame {
   
    public PaneImage () {
       
        super();
        setSize( 100, 100 );
       
        JPanel backPanel = new BackgroundPanel();
        this.getContentPane().add(backPanel);
       
        JButton t = new JButton( "hello" );
       
        backPanel.add( t );
       
        setVisible( true );
       
    }
 
    public static void main ( String [] args ) {
       
        PaneImage pi = new PaneImage ();
       
    }
 
class BackgroundPanel extends JPanel
{
  protected Image bgImage = /* An Image */;

  public BackgroundPanel()
  {
    super(true);
    this.setLayout(new BorderLayout());
    setOpaque(false);
  }

  public void paint(Graphics gr)
  {
    gr.drawImage(bgImage, 0 ,0 ,this);
    super.paint(gr);
  }
} // BackgroundPanel
   
}

How would I then implement your above 'image' code into this? :o)

Thanks,
-R
0
 
rubberdiAuthor Commented:
ie; I don't understand how to use that class. :o\ Despite your comments..
:o|  lol (Sorry for my ignorance).

Thanks :o)
-R
0
 
rubberdiAuthor Commented:
Thanks alot Johnny.
That's very useful, and is what I wanted. :o)

Could you elaborate a bit on sciuriware's code, for applying an image to the background of a JPanel??

Thanks :o)
-R
0
 
rubberdiAuthor Commented:
Actually, I'm having a SLIGHT problem here:
Johnny; What I would like to do is; arrange the JPanels in different locations, for alignment of components. (Sort of, like 'tables' in HTML).
What I tried was to change:

          panel[1].setBounds(0,0,panel[0].getSize().width - 50,panel[0].getSize().height - 50);
          panel[2].setBounds(0,0,panel[1].getSize().width - 50,panel[1].getSize().height - 50);

to:

          panel[1].setBounds(0,0,panel[0].getSize().width - 50,40);
          panel[2].setBounds(0,40,panel[1].getSize().width - 50,20);

Note; the '40', in panel[2], which I was hoping would make the panel appear 40pix down from the top corner of the frame. But, it dont seem to work  :o\ ... Is there a way to align panels like that?

Thank you :)
-R
0
 
JohnnyAffaCommented:
rubberdi, the inner most panel is panel[0] and within panel[0] is panel[1] and withing panel[1] is panel[2] and so on.  which panel do you want 40 pixels down? (they are indicated by colours so use colours to cut confusion)

re table:

so so dont really want panels inside panels but panel side by side?

re images:

do you only want to display an image? if so use a label instead of a panel and set their setBounds() as in my previous example

to get image use

Image image = Toolkit.getDefaultToolkit().getImage([location]);
0
 
rubberdiAuthor Commented:
Hi Johnny,
Yer, I would like the panels side-by-side  -  Could you demonstrate that please? :)

I don't just want to display an image. I would like an image in the background, then components, ie; buttons, on top.

Thanks alot,
-R
0
 
sciuriwareCommented:
rubberdi, how many questions are you gonna ask for only 100 points?

If you have new questions, ask new ones.

;JOOP!
0
 
JohnnyAffaCommented:
rubberdi, like sciuiware said how many questions you want answered?.....lololololol

if you want a side by side arrangement use GridLayout(int rows,int cols)

eg contentPane.setLayout(new GridLayout(10,10));

10 columns 10 rows

when you add a component the order is left to right top down, like when you read.

re images

once you have an image you need to override the frame's paint method

public void paint(Graphics g)
{
         Graphics h = panel[0].getGraphics();
         h.drawImage([image],[x],[y],[width],[height],this);
 or
     h.drawImage([image],[x],[y],this); // which will display the image in its actual size

        this.paintComponents(g);
}
0
 
rubberdiAuthor Commented:
>"rubberdi, how many questions are you gonna ask for only 100 points?"
:o\ oops.  -lol
Sorry.. I hope that you don't think that I've been disrespecting you, or intentionally taking advantage.

Soz. And thanks.

Do you mind me just asking for a bit more help on the above 'solution'? :o\ (Or am I REALLY pushing it? lol).

>"contentPane.setLayout(new GridLayout(10,10));"
How would I then add components to these rows/columns? (I suck at UIs -lol :( ).
Could you write a VERY simply program to quickly demonstrate it? :o\

THANKS!!!!!!!!!!!!!!! :D
-R
0
 
rubberdiAuthor Commented:
Actually.. I think I've got it now  :D

I'm going to close the Q.. and thanks ALOT for you help guys  (and your patience ;) ) hehe..

thank you,
-R
0
 
rubberdiAuthor Commented:
:'(  ermmm......
What have I done wrong?..

//-------8<---------Shading.java--------------------------------------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class Spacing extends JFrame
{
     JPanel panel[] = new JPanel[3];
     JButton b;
     Image image = Toolkit.getDefaultToolkit().getImage( "img.jpg" );

     public Spacing()
     {
          this.setInterface();
     }

     private void setInterface()
     {
          this.setBounds(50,80,400,400);

          Container contentPane = this.getContentPane();
         
          panel[0] = new JPanel(null);

          panel[1] = new JPanel(null);
          panel[1].setBackground(Color.blue);

          panel[0].add(panel[1]);

          panel[2] = new JPanel();
          panel[2].setBackground(Color.yellow);

          panel[0].add(panel[2]);

          contentPane.add(panel[0]);

          this.setVisible(true);
     }

     public void paint(Graphics g)
     {
          Graphics h = panel[0].getGraphics();
          h.drawImage(image, 0, 0, panel[0].getSize().width, panel[0].getSize().height, this);
          panel[1].setBounds(0, 30, panel[0].getSize().width, 50);
          panel[2].setBounds(0, 100, panel[0].getSize().width, 50);
         
          this.paintComponents(g);
     }

     public void processWindowEvent(WindowEvent event)
     {
          if ( event.getID() == WindowEvent.WINDOW_CLOSING )
               System.exit(0);
     }

     public static void main(String args[])
     {
          new Spacing();
     }
}
//-------8<---------Shading.java--------------------------------------------------------------------------------------------

:o\ I just get a VERY quick flicker of the image, then panel[0] is just grey! (with no image) :o\

??? ;)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.