本例是为了体现Java中布局的使用,在一个Frame上添加了两个Panel,在两个Panel上分别体现了一个Butoon,一个Label和一个TextField的边框布局和网格布局,而Frame本身使用了网格布局。
import java.awt.*;
import java.awt.event.*;
class TwoLayout extends WindowAdapter implements WindowListener,ActionListener
{Frame f;Panel pborder,pgrid;
Label lborder,lgrid;TextField tborder,tgrid;Button bborder,bgrid;
public static void main(String args[])
{TwoLayout a=new TwoLayout();
a.execute();
}
public void execute()
{f=new Frame("布局");
f.setLayout(new GridLayout(2,1));
f.addWindowListener(this);
pborder=new Panel();pgrid=new Panel();
f.add(pborder);f.add(pgrid);
pborder.setLayout(new BorderLayout());
pgrid.setLayout(new GridLayout(3,1));
lborder=new Label();tborder=new TextField();bborder=new Button("边框布局复制");
lgrid=new Label();tgrid=new TextField();bgrid=new Button("网格布局复制");
lborder.setBackground(Color.yellow);lgrid.setBackground(Color.yellow);
pborder.add("East",bborder);pgrid.add(lgrid);
pborder.add("North",lborder);pgrid.add(tgrid);
pborder.add("Center",tborder);pgrid.add(bgrid);
bborder.addActionListener(this);
bgrid.addActionListener(this);
f.setSize(300,150);f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{if(e.getSource()==bborder)
{String s=lborder.getText()+tborder.getText();
lborder.setText(s);
}
else
{String s=lgrid.getText()+tgrid.getText();
lgrid.setText(s);
}
}
public void windowClosing(WindowEvent e)
{System.exit(0);
}
}
评论