Tue, April 4, 2006
レイアウトマネージャの自作(VerticalLayout)
FlowLayoutは横にコンポーネントを配置していきますが、 これとは逆に縦に配置していくレイアウトマネージャを自作してみました。
ちなみに、 javax.swing.Box を使用して同じようなことを実現できます。 実際に縦にコンポーネントを配置したい場合、 javax.swing.Boxで済ませることができないか、先に検討した方がよいでしょう。
VerticalLayout
VerticalLayout.java
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
public class VerticalLayout implements LayoutManager {
private int _vgap;
public VerticalLayout(){
this(5);
}
public VerticalLayout(int vgap){
_vgap=vgap;
}
private boolean _widthPreferred;
/**
* 横幅をコンポーネントのPreferredSizeにするか
* (それとも親のコンテナの横幅に揃えるか=いっぱいまで広げる)かの指定.
*/
public void setWidthPreferred(boolean b){
_widthPreferred=b;
}
/**
* 横幅をコンポーネントのPreferredSizeにするか
* (それとも親のコンテナの横幅に揃えるか=いっぱいまで広げる)かを返す.
*/
public boolean isWidthPreferred(){
return _widthPreferred;
}
public void addLayoutComponent(String arg0, Component arg1) {
// TODO Auto-generated method stub
}
public void removeLayoutComponent(Component arg0) {
// TODO Auto-generated method stub
}
public Dimension preferredLayoutSize(Container arg0) {
return computelayoutSize(arg0);
}
public Dimension minimumLayoutSize(Container arg0) {
return computelayoutSize(arg0);
}
/**
* 現在のところ,左詰にします.
*/
public void layoutContainer(Container parent) {
Component[] components=parent.getComponents();
Dimension size=parent.getSize();
Component c;
int parentWidth=parent.getSize().width;
int currentY=0;
for(int i=0; i<components.length; i++){
int currentH=components[i].getPreferredSize().height;
c=components[i];
int x=0;
int y=0+currentY;
int width=parentWidth;
if( isWidthPreferred() ){
width=components[i].getPreferredSize().width;
}
c.setBounds(x,y,width,currentH);
currentY=currentY+currentH+_vgap;
}
}
private Dimension computelayoutSize(Container parent){
Component[] components=parent.getComponents();
int w=0;
for(int i=0; i<components.length; i++){
int w1=components[i].getPreferredSize().width;
w=Math.max(w,w1);
}
int h=0;
for(int i=0; i<components.length; i++){
int h0=components[i].getPreferredSize().height;
h+=h0;
}
{
//w=w+_hgap;
int count=components.length;
h=h+(count)*_vgap;
}
return new Dimension( w,h );
}
}
レイアウトマネージャの使用例
import javax.swing.*;
public class Test2 extends JPanel{
public Test2(){
super();
setLayout(new VerticalLayout());
for(int i=0; i<20; i++){
add(new JLabel("test"+i));
}
}
}