GridLayout所切割出来的版面就如同表格一般整齐,加入的组件会按顺序由左至右、由上至下摆放,所以无法直接指定要摆放的区域。除此之外,组件放入后会变成方形,所以不适合放入JButton这类组件中,而比较适合加入JPanel。GirdLayout类的信息如下:
public class GridLayout extends Object implements LayoutManager,Serializable
构造函数:
public GridLayout();
public GridLayout(int rows,int cols);
public GridLayout(int rows,int cols,int hgap,int vgap);
函数作用:建立一个表格的版面对象。rows代表有几行,cols代表有几列;hgap是组件之间的水平距离,vgap是组件之间的竖直距离
import java.applet.Applet;
import java.awt.*;public class GrdLyoutTest extends Applet{
static final int n = 4;
public void init(){
setLayout(new GridLayout(n,n));
setFont(new Font("Times NEW Roman",Font.BOLD,30));
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
int k = i*n + j;
if(k>0){
add(new Button(""+k));
}
}
}
}
}
exp2:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridLayoutTest2 extends JFrame {
JButton button = new JButton("Click me");
JPanel panel = new JPanel(new FlowLayout());
public GridLayoutTest2(){
final JFrame frame = this;
this.getContentPane().add(panel, BorderLayout.SOUTH);
panel.add(button);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
showLoginDialog(frame);
}
});
this.setSize(300, 200);
this.setTitle("show dialog");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.show();
}
void showLoginDialog(JFrame frame){
JPanel p = new JPanel(new GridLayout(0,1));
JTextField tfUserName = new JTextField();
JPasswordField tfPassword = new JPasswordField();
p.add(new JLabel("Username: "));
p.add(tfUserName);
p.add(new JLabel("Password: "));
p.add(tfPassword);
if(JOptionPane.showConfirmDialog(frame,
p,
"Login",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION){
System.out.println("USER Name:"+tfUserName.getText());
System.out.println("Password:"+new String(tfPassword.getPassword()));
}
}
public static void main(String[] args){
GridLayoutTest2 frmae = new GridLayoutTest2();
}
}