创建自定义布局管理器

本次编写小编只是为了说明如何自定义创建布局管理器,所以只是简单举例。
首先自定义的布局管理器要继承LayoutManager 接口,然后实现借口里的方法,接着的布局只需在layoutContainer(Cotainer parent)编写就行

自定义布局类:

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
在这里插入代码片

测试类:

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);
}
}

在这里插入代码片
发布了130 篇原创文章 · 获赞 16 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/feiqipengcheng/article/details/104877520
今日推荐