Solved

Panel margin and alignment

Posted on 2004-09-05
17
715 Views
Last Modified: 2013-11-23
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
0
Comment
Question by:rubberdi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 4
  • 3
  • +1
17 Comments
 
LVL 24

Expert Comment

by:sciuriware
ID: 11983805
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
 
LVL 9

Expert Comment

by:DrWarezz
ID: 11983822
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
 
LVL 24

Expert Comment

by:sciuriware
ID: 11983840
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:rubberdi
ID: 11983868
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
 
LVL 24

Assisted Solution

by:sciuriware
sciuriware earned 30 total points
ID: 11983902
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
 

Author Comment

by:rubberdi
ID: 11983911
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
 

Author Comment

by:rubberdi
ID: 11983966
ie; I don't understand how to use that class. :o\ Despite your comments..
:o|  lol (Sorry for my ignorance).

Thanks :o)
-R
0
 
LVL 3

Accepted Solution

by:
JohnnyAffa earned 70 total points
ID: 11983988
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
 

Author Comment

by:rubberdi
ID: 11984010
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
 

Author Comment

by:rubberdi
ID: 11984066
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
 
LVL 3

Expert Comment

by:JohnnyAffa
ID: 11984276
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
 

Author Comment

by:rubberdi
ID: 11984290
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
 
LVL 24

Expert Comment

by:sciuriware
ID: 11984308
rubberdi, how many questions are you gonna ask for only 100 points?

If you have new questions, ask new ones.

;JOOP!
0
 
LVL 3

Expert Comment

by:JohnnyAffa
ID: 11984347
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
 

Author Comment

by:rubberdi
ID: 11984365
>"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
 

Author Comment

by:rubberdi
ID: 11984474
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
 

Author Comment

by:rubberdi
ID: 11984598
:'(  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

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question