/* Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
This code is for educational purposes only. Use at own risk.*/

1. import javax.swing.* ; 

2. import java.awt.* ; 

3. import java.awt.event.*; 

4.  

5. public class GBLaySw 

6.   extends JApplet implements ActionListener 

7.

8.   GridBagLayout gbl ; 

9.   GridBagConstraints gbc ; 

10.  

11.   JPanel p1, p2 ; 

12.   Container cp ; 

13.  

14.   JButton btop, btn ; 

15.   JLabel lbl ; 

16.   JTextField tf ; 

17.   JCheckBox cbx ; 

18.  

19.   int cnt = 1

20.  

21.   public GBLaySw ( ) 

22.   { 

23.     gbl = new GridBagLayout() ; 

24.     gbc = new GridBagConstraints() ; 

25.  

26.     p1 = new JPanel() ; 

27.     p2 = new JPanel() ; 

28.     btop = new JButton ( "Press me hard" ) ; 

29.  

30.     lbl = new JLabel ( "Laybull 1,1" )  ; 

31.     lbl.setBackground ( Color.cyan ) ; 

32.     lbl.setOpaque(true); 

33.     btn =  new JButton ( "Pressure 2,2" ) ; 

34.     cbx = new JCheckBox ( "Check,mate 3,3" , true ) ; 

35.     cbx.setBackground ( Color.cyan ) ; 

36.     tf = new JTextField ( "Typoo 4,1" ) ; 

37.   } 

38.   public void init() 

39.   { 

40.     cp = getContentPane(); 

41.     p1.add ( btop ) ; 

42.     p2.setLayout ( gbl ) ; 

43.  

44.     addthosecomponents ( cnt ) ; 

45.  

46.     cp.setLayout ( new BorderLayout () ) ; 

47.     p1.setBackground ( Color.yellow ) ; 

48.     p2.setBackground ( Color.pink ) ; 

49.     cp.add ( p1, BorderLayout.NORTH ) ; 

50.     cp.add ( p2, BorderLayout.CENTER ) ; 

51.  

52.      btop.addActionListener ( this ) ; 

53.   } 

54.  

55.   public void actionPerformed( ActionEvent ev ) 

56.   { 

57.     p2.removeAll () ; 

58.      p2.revalidate () ; 

59.     ++cnt ; 

60.     if ( cnt > 4

61.       cnt = 1

62.     addthosecomponents ( cnt ) ; 

63.   } 

64.   void addthosecomponents ( int nr ) 

65.   { 

66.     gbc.weightx = 1.0

67.     gbc.weighty = 1.0

68.     gbc.anchor = GridBagConstraints.CENTER

69.     switch ( nr  ) 

70.     { 

71.     case 1

72.       gbc.fill = GridBagConstraints.BOTH

73.       break

74.     case 2

75.       gbc.fill = GridBagConstraints.HORIZONTAL

76.       break

77.     case 3

78.       gbc.fill = GridBagConstraints.VERTICAL

79.       break

80.     case 4

81.       gbc.fill = GridBagConstraints.NONE

82.       break

83.     } //end switch 

84.  

85.     gbc.gridx = 1

86.     gbc.gridy = 1

87.  

88.     p2.add ( lbl, gbc ) ; 

89.  

90.     gbc.gridx = 2

91.     gbc.gridy = 2

92.  

93.     p2.add ( btn, gbc ) ; 

94.  

95.     gbc.gridx = 3

96.     gbc.gridy = 3

97.  

98.     p2.add ( cbx, gbc ) ; 

99.  

100.     gbc.gridx = 4

101.     gbc.gridy = 1

102.  

103.     p2.add ( tf, gbc ) ; 

104.  

105.     p2.revalidate () ; 

106.   } 

107.