Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: My Custom Layout (VERY EASY TO USE)

  1. #1
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default My Custom Layout (VERY EASY TO USE)

    NOTE: UPDATED CODE A FEW POSTS DOWN

    So a few months ago I got really annoyed with the stupidity of all of the layouts Java supplies for organizing components. I said to myself, why cant I just tell a GUI element to be placed at this specific coordinate? Then I found SpringLayout. After a few minutes of that, I had a minor stroke. SpringLayout is the most versatile of the Java supplied layouts, but it is incredibly ridiculous and confusing for any normal human to understand. So, I figured I'd create my own layout that would use the versatility of SpringLayout and provide me with my desired coordinate placing. So, for those who have gotten really pissed off at Java Layouts like I have, here is my Coordinate Layout code and a small test program for you to see how it works. It is very simple to use and works beautifully. If there are any questions, I'll be happy to answer them.

    Layout Class:
    import javax.swing.SpringLayout;
    import java.awt.Container;
    import java.awt.Component;
     
    public class CoordinateLayout extends SpringLayout
    {
    	//Container Variable
    	Container cont;
     
    	//Constructor
        public CoordinateLayout(Container ct) 
        {
        	//Extend SpringLayout
        	super();
        	//Set Layout to Container
        	ct.setLayout(this);
        	//Initialize Container Variable
        	cont = ct;
        }
     
        //Method to Add Components -- (0,0) is top left of container
        public void addComponent(Component comp, int x, int y)
        {
        	//Adds Component to Container
        	cont.add(comp);
        	//Set both x and y SpringLayout contraints
        	super.putConstraint(SpringLayout.WEST, comp, x, SpringLayout.WEST, cont);
    		super.putConstraint(SpringLayout.NORTH, comp, y, SpringLayout.NORTH, cont);
        }
    }

    Test Class:
    import javax.swing.*;
    import java.awt.*;
     
    public class CoordinateLayoutTest 
    {
     
        public static void main(String[] args) 
        {
        	//Create Frame and Panel
        	JFrame mainFrame = new JFrame("TEST");
        	JPanel first = new JPanel();
     
        	//Create Layout and send it the Panel
        	CoordinateLayout layout = new CoordinateLayout(first);
     
        	//Create components
        	JLabel l1 = new JLabel("First Name:");
        	JTextField b1 = new JTextField(10);
    		JLabel l2 = new JLabel("Last Name:");
    		JTextField b2 = new JTextField(10);
    		JLabel l3 = new JLabel("Home City:");
    		JTextField b3 = new JTextField(10);
    		JLabel l4 = new JLabel("Home State:");
    		JTextField b4 = new JTextField(10);
    		JLabel l5 = new JLabel("Account Number:");
    		JTextField b5 = new JTextField(10);
    		//Add components
    		layout.addComponent(l1,5,5);
    		layout.addComponent(b1,105,5);
    		layout.addComponent(l2,5,35);
    		layout.addComponent(b2,105,35);
    		layout.addComponent(l3,5,65);
    		layout.addComponent(b3,105,65);
    		layout.addComponent(l4,5,95);
    		layout.addComponent(b4,105,95);
    		layout.addComponent(l5,5,125);
    		layout.addComponent(b5,105,125);
     
    		//Simplify adding components by creating JLabels when you use them
    		/*
        	JTextField b1 = new JTextField(10);
    		JTextField b2 = new JTextField(10);
    		JTextField b3 = new JTextField(10);
    		JTextField b4 = new JTextField(10);
    		JTextField b5 = new JTextField(10);
    		layout.addComponent(new JLabel("First Name:"),5,5);
    		layout.addComponent(b1,105,5);
    		layout.addComponent(new JLabel("Last Name:"),5,35);
    		layout.addComponent(b2,105,35);
    		layout.addComponent(new JLabel("Home City:"),5,65);
    		layout.addComponent(b3,105,65);
    		layout.addComponent(new JLabel("Home State:"),5,95);
    		layout.addComponent(b4,105,95);
    		layout.addComponent(new JLabel("Account Number:"),5,125);
    		layout.addComponent(b5,105,125);
    		*/
     
        	//Finish creating Frame
        	mainFrame.setSize(300,300);
        	mainFrame.setContentPane(first);
        	mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        	mainFrame.setVisible(true);
        }   
    }
    Last edited by aussiemcgr; August 5th, 2010 at 01:02 PM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: My Custom Layout (VERY EASY TO USE)

    What are all the hardcoded x,y values? Is there a preprocessor that generates them? I hope you don't have to manually compute them.
    What happens if you need to insert a line of components at the top?

    The x,y values should be relative to the preceding component so that if you insert a line, you only have to change one line, not all of the following.

  3. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: My Custom Layout (VERY EASY TO USE)

    Back when I made it, I was going to add a method to do that, but I couldn't figure out how to get the width/height of the components.

    I've found manually computing them isn't much of problem after using it for awhile. Plus you can line up textboxes, labels, ect. with the manually computed numbers.

    Alternatively, I've found its possible to put the addComponent method in a loop that adjusts the x,y coordinates appropriately based on my specific needs.

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: My Custom Layout (VERY EASY TO USE)

    You can get the width and height of a component using the getWidth() and getHeight() methods, or alternatively call the getSize() method to get a dimension object containing the width and height.

    I'm pretty sure there's a simple method call to get the relative location of one component to another component, but I can't think of it off the top of my head. However, This should work to fullfill this purpose (this is untested code):

    /**
     * Gets the a point representing the relative coordinate of component's top-left corner to base's top-left corner
     */
    public static Point getRelativePosition(Component base, Component component)
    {
         Point basePoint = base.getLocationOnScreen();
         Point compPoint = component.getLocationOnScreen();
         return new Point(compPoint.x - basePoint.x, compPoint.y - basePoint.y);
    }

  5. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: My Custom Layout (VERY EASY TO USE)

    Quote Originally Posted by helloworld922 View Post
    I'm pretty sure there's a simple method call to get the relative location of one component to another component, but I can't think of it off the top of my head. However, This should work to fullfill this purpose (this is untested code):
    [/highlight]
    Well, since my layout uses SpringLayout, the other elements can be offset relative to the other elements.

    Now if the problem is inserting a row on components on the top, I'm sure I could put in a method to shift the y values of the other components based on the height of the row being inserted. Unfortunately, it may require the user to send an array or something of components incase the user doesnt want some of the components shifted down (if the row doesnt take up the entire length or something).

  6. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: My Custom Layout (VERY EASY TO USE)

    You can get the width and height of a component using the getWidth() and getHeight() methods, or alternatively call the getSize() method to get a dimension object containing the width and height.
    Cant get those to work. They just return 0... Thats the reason I couldnt get the addCenter method going...

    I believe those methods only work if you give the components preferred sizes, which i dont want to do for this. I want them to keep whatever size comes naturally to them.

  7. #7
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: My Custom Layout (VERY EASY TO USE)

    Ok, so continuing with this, I have made some changes that might make it more usable. I could use some suggestions and some feedback.

    import javax.swing.SpringLayout;
    import java.awt.Container;
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.*;
     
    public class CoordinateLayout extends SpringLayout
    {
    	public static void main(String args[])
    	{
    		JFrame frame = new JFrame("Test");
    		JPanel panel = new JPanel();
    		frame.setContentPane(panel);
    		frame.setSize(700,400);
    		CoordinateLayout layout = new CoordinateLayout(panel);
    		layout.setSize(frame);
     
    		//Standard addComponentMethod
    		JButton button = new JButton("Standard Placing");
    		layout.addComponent(button,5,5);
     
    		//Centered addComponentMethod
    		JButton button2 = new JButton("Centered Placing");
    		layout.addCenter(button2,30);
     
    		//Vertical Array of Components
    		Component[] vertArr = new Component[5];
    		for(int i=0;i<vertArr.length;i++)
    		{
    			vertArr[i] = new JTextField("Vertical Fields");
    		}
    		layout.addComponent(vertArr,5,40,30,CoordinateLayout.VERTICAL);
     
    		//Horizontal Array of Components
    		Component[] horiArr = new Component[5];
    		for(int i=0;i<horiArr.length;i++)
    		{
    			horiArr[i] = new JTextField("Horizontal Fields");
    		}
    		layout.addComponent(horiArr,150,5,5,CoordinateLayout.HORIZONTAL);
     
    		//Grid Layout with JLabels and JTextFields
    		Component[][] gridArr = new Component[5][2];
    		for(int i=0;i<gridArr.length;i++)
    		{
    			gridArr[i][0] = new JLabel("Label "+i+":");
    			gridArr[i][1] = new JTextField("Grid Field");
    		}
    		layout.addComponent(gridArr,150,40,30,CoordinateLayout.VERTICAL);
     
    		frame.setVisible(true);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	}
     
     
    	//Variables
    	Container cont;
    	int width = 0;
    	int height = 0;
     
    	//Constants
    	static final int VERTICAL = 0;
    	static final int HORIZONTAL = 1;
     
    	//Constructor
        public CoordinateLayout(Container ct)
        {
        	super();
        	ct.setLayout(this);
        	cont = ct;
        }
     
    	/*
    	 *Method to indicate desired size of cont.
    	 *w = width.
    	 *h = height
    	*/
        public void setSize(int w,int h)
        {
        	width = w;
        	height = h;
        }
    	/*
    	 *Method to indicate desired size of cont.
    	 *frame = the Component which has its Content Pane set to cont
    	*/
        public void setSize(Component frame)
        {
        	width = frame.getWidth();
        	height = frame.getHeight();
        }
    	/*
    	 *Standard Method to Add Components:
    	 *comp = Component being added.
    	 *x = desired x coordinate
    	 *y = desired y coordinate
    	 */
        public void addComponent(Component comp, int x, int y)
        {
        	cont.add(comp);
        	super.putConstraint(SpringLayout.WEST, comp, x, SpringLayout.WEST, cont);
    		super.putConstraint(SpringLayout.NORTH, comp, y, SpringLayout.NORTH, cont);
        }
     
    	/*
    	 *Method to add multiple Components in a Grid-Type Layout. This method's intended use is to display Labels next to Components
    	 *Pre-Condition: One of the setSize methods have been implemented.
    	 *
    	 *comps = 2 Dimensional Array of Components. For this method, it is recomended that the inclusive array has a length of 2 (Label and Component)
    	 *xV = desired starting X coordinate
    	 *yV = desired starting Y coordinate
    	 *space = desired spacing between components.
    	 *type = Either CoordinateLayout.VERTICAL or CoordinateLayout.HORIZONTAL to indicate which direction the spacing will occur. This method currently only supports VERTICAL spacing
    	 */
        public void addComponent(Component[][] comps, int xV, int yV, int space, int type)
        {
        	int x = xV;
        	int y = yV;
     
        	if(type == 0)
        	{
        		int largestWidth = super.getConstraints(comps[0][0]).getWidth().getValue();
        		for(int i=1;i<comps.length;i++)
        		{
        			Component[] com = comps[i];
        			if(super.getConstraints(com[0]).getWidth().getValue()>largestWidth)
        				largestWidth = super.getConstraints(com[0]).getWidth().getValue();
        		}
        		largestWidth+=5;
        		for(int i=0;i<comps.length;i++)
        		{
        			Component[] com = comps[i];
        			for(int xu=0;xu<com.length;xu++)
        			{
        				addComponent(com[xu],x,y+(space*i));
        				x+=largestWidth;
        			}
        			x = xV;
        			y += super.getConstraints(comps[i][0]).getHeight().getValue();
        		}
        	}
        	else
        		System.out.println("Not Supported Yet");
        }
    	/*
    	 *Method to add multiple Components either Vertically or Horizontally
    	 *Pre-Condition: One of the setSize() methods have been implemented
    	 *
    	 *comps = 1 Dimensional array of Components
    	 *xV = desired starting X coordinate
    	 *yV = desired starting Y coordinate
    	 *space = desired spacing between Components
    	 *type = Either CoordinateLayout.VERTICAL or CoordinateLayout.HORIZONTAL to indicate which direction the spacing will occur.
    	 */
        public void addComponent(Component[] comps, int xV, int yV, int space, int type)
        {
        	int v = 0;
        	for(int i=0;i<comps.length;i++)
        	{
        		int x = xV;
        		int y = yV;
        		if(type == 0)
        			y += (space+v)*i;
        		else
        			x += (space+v)*i;
     
        		addComponent(comps[i],x,y);
        		if(type == 0)
        			v = super.getConstraints(comps[i]).getHeight().getValue();
        		else
        			v = super.getConstraints(comps[i]).getWidth().getValue();
     
        	}
        }
    	/*
    	 *Method to add a Component centered along the X Axis.
    	 *Pre-Condition: One of the setSize() methods have been implemented
    	 *
    	 *comp = Component to be centered
    	 *y = desired Y coordinate
    	 */
        public void addCenter(Component comp, int y)
        {
        	int widthC = super.getConstraints(comp).getWidth().getValue();
        	int windowWidth = width;
        	int loc = (windowWidth-widthC)/2;
        	addComponent(comp,loc,y);
        }
    }
    Last edited by aussiemcgr; August 5th, 2010 at 01:01 PM.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: My Custom Layout (VERY EASY TO USE)

    It'd be a bit more useful if you added a main() method that would use the above classes and methods and demo how to use them.
    It could be commented out when moving to production.

  9. #9
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: My Custom Layout (VERY EASY TO USE)

    Ok, I made a main and updated the code, and I found a small change I had to make with one of the methods (clearly didnt extensively test it enough), so its a good thing I did.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: My Custom Layout (VERY EASY TO USE)

    Same points as before, how does a user come up with the x,y points to place the components?
    Is there a tool to compute them and store them in the code.
    I hope it doesn't have to be done manually.

  11. #11
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: My Custom Layout (VERY EASY TO USE)

    Well, for the addComponent(Component,int,int) method, the user will have to compute those manually because how else will the layout know where to put the components? For the addCenter(Component,int) method, the user has to indicate the Y-Coordinate and it will figure out the X based on the size that was specified in one of the setSize() methods. For the other two addComponent methods, the user has to specify where they want the first Component to be placed, but the rest of the locations are computed by the space and type parameters.

    The intention of this layout is to have a Coordinate-Based Layout which does not auto-resize Components and will be used when hardcoding the GUI (not using a IDE with a built-in GUI designer). Because of those intentions, I dont know how I could write code that would just know how the user wants their GUI setup.

Similar Threads

  1. How do you layout these components centered
    By robertbob in forum AWT / Java Swing
    Replies: 2
    Last Post: May 24th, 2010, 11:52 PM
  2. an easy clear java programming tutorial
    By zkil_jpf in forum The Cafe
    Replies: 2
    Last Post: April 22nd, 2010, 08:40 AM
  3. Custom Java stack class (with generics) problem
    By TBBucs in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 7th, 2010, 02:25 AM
  4. A Few Quick, Easy Questions
    By TheAsianMenace in forum Object Oriented Programming
    Replies: 1
    Last Post: February 24th, 2010, 02:47 PM
  5. String + Compare // Might be too easy for ya
    By Jangan in forum Java Theory & Questions
    Replies: 1
    Last Post: October 18th, 2009, 05:40 PM