import java.awt.*; 
import java.awt.event.*;
import javax.swing.*;

public class LayoutTest {
 
    private LayoutTestFrame test; 
    
    public static void main(String[] args) {
	LayoutTest lt = new LayoutTest();
	lt.test = new LayoutTestFrame(); 

	GridBagLayout layout = new GridBagLayout();

	lt.test.getContentPane().setLayout(layout); 
	
	GridBagConstraints gbc = new GridBagConstraints();
	gbc.fill = GridBagConstraints.BOTH;
	gbc.anchor = GridBagConstraints.NORTHWEST;
	gbc.insets = new Insets(0, 0, 5, 5);

	// add components
	JButton ok = new JButton("ok"); 
	ok.setBackground(Color.green); 
	ok.setOpaque(true);

	JButton cancel = new JButton("cancel"); 
	cancel.setBackground(Color.red);
	cancel.setOpaque(true);
	
	JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
	buttonPanel.add(ok); 
	buttonPanel.add(cancel);

	JLabel question = new JLabel("Save file?"); 
	question.setBackground(Color.yellow);
	question.setOpaque(true);
	
	JTextField filename = new JTextField(20);

	// nested class
	class MyCanvas extends JPanel {
	    public Dimension getPreferredSize() { return new Dimension(80,80); }

	    public void paintComponent(Graphics g){
		super.paintComponent(g);
		setBackground(Color.white);
		setOpaque(true);
		g.drawString("test",10,20); 
	    }
	}
	MyCanvas myCanvas = new MyCanvas();
	
	lt.addUsingGBL(question, gbc, 0, 0, 3, 1);
	lt.addUsingGBL(filename, gbc, 0, 1, 3, 1); 
	lt.addUsingGBL(myCanvas, gbc, 3, 0, 3, 3); 
	lt.addUsingGBL(buttonPanel, gbc, 0, 2, 3, 1); 

	lt.test.setVisible(true); 
    }

    private void addUsingGBL(Component comp, GridBagConstraints gbc, 
			     int x, int y, int w, int h) {
	gbc.gridx = x; 
	gbc.gridy = y;
	gbc.gridwidth = w; 
	gbc.gridheight = h;
	test.getContentPane().add(comp,gbc);
    }
}

class LayoutTestFrame extends JFrame {
    private WindowHandler wh;

    public LayoutTestFrame() {
	getContentPane().setBackground(Color.lightGray);
	setSize(400,300);
	setLocation(100,100);
	wh = new WindowHandler(this); 
	addWindowListener(wh);
    }
}
 
class WindowHandler extends WindowAdapter {
    private Container parent; 

    public WindowHandler(Container parent){
	this.parent = parent; 
    }
    
    public void windowClosing(WindowEvent evt){ 
	((Frame) parent).dispose();
	System.exit(0); 
    }
}

