Create a custom layout manager

The preparation of small series just to illustrate how to create a custom layout manager, it is just a simple example.
First custom layout manager to inherit LayoutManager interface, and then implement an excuse in the method, then the layout just in layoutContainer (Cotainer parent) written on the line

Custom layout classes:

import java.awt.*;
import java.io.Serializable;

class textLayout implements LayoutManager,Serializable{

	  public void addLayoutComponent( String name, Component comp ){}

	   public Dimension minimumLayoutSize( Container parent ){
	                   return new Dimension( 0, 0 );
	         }//end minimumLayoutSize
	    public Dimension preferredLayoutSize( Container parent ){

	                   return minimumLayoutSize( parent );
	         }//ed preferredLayoutSize
	         public void removeLayoutComponent( Component comp ){

	         }//end removeLayoutComponent
			
	         public void layoutContainer( Container p ){
   int n=p.getComponentCount();
   int x=0,y=0;
   for(int i=0;i<n;i++)
   {Component c=p.getComponent(i);
   c.setBounds(x,y, c.getPreferredSize().width, c.getPreferredSize().height);
   x+=c.getPreferredSize().width;
   y+=c.getPreferredSize().height;
   }
	   	  }//end addLayoutComponent
	}//end class
在这里插入代码片

Test categories:

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Dimension;
import java.net.URL;

import javax.swing.*;
import javax.swing.JLabel;

public class a extends JApplet{
public a() {
	JPanel p=new JPanel();
	p.setLayout(new textLayout());
	p.add(new JLabel("1"));
	p.add(new JLabel("2"));
	p.add(new JLabel("3"));
	p.add(new JLabel("4"));
	add(p);
}
}

在这里插入代码片
Published 130 original articles · won praise 16 · views 30000 +

Guess you like

Origin blog.csdn.net/feiqipengcheng/article/details/104877520