9.16. (Optional GUI) Inheriting GUI Components |
You learned how to create frames in the optional GUI sections in the preceding two chapters. The frames were created in the main method. A frame created in this way cannot be reused. It is better to declare a custom frame class by extending the JFrame class. To demonstrate , let us rewrite Listing 8.11, TwoButtons.java, using a custom frame class, as shown in Listing 9.12.
1 import javax.swing.*; 2 import java.awt.*; 3 4 public class CustomFrame extends JFrame { 5 public CustomFrame() { 6 // Set FlowLayout for the frame 7 FlowLayout layout = new FlowLayout(); 8 setLayout(layout); 9 10 // Add two buttons to frame 11 JButton jbtOK = new JButton( "OK" ); 12 JButton jbtCancel = new JButton( "Cancel" ); 13 add(jbtOK); 14 add(jbtCancel); 15 } 16 17 public static void main(String[] args) { 18 JFrame frame = new CustomFrame(); 19 frame.setTitle( "Window 1" ); 20 frame.setSize( 200 , 150 ); 21 frame.setLocation( 200 , 100 ); 22 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 23 frame.setVisible( true ); 24 } 25 } |
The CustomFrame class extends JFrame to inherit all accessible methods from JFrame . Invoking new CustomFrame() in line 18 creates an instance of CustomFrame , which is also an instance of JFrame . The constructor of CustomFrame sets a FlowLayout for the frame in line 8 and adds two buttons in lines 13 “14. The CustomFrame class can now be reused, as shown in Listing 9.13.
1 import javax.swing.*; 2 3 public class UseCustomFrame { 4 public static void main(String[] args) { 5 JFrame frame = new CustomFrame(); 6 frame.setTitle( "Use CustomFrame" ); 7 frame.setSize( 200 , 150 ); 8 frame.setLocation( 200 , 100 ); 9 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 10 frame.setVisible( true ); 11 } 12 } |