// MyPanel.java // -- continuing the example of EmptyFrame1.java /** * Our main goal is to add panels to a frame. * In swing, panels are extensions of JPanels, and the main * method we need to override is the "paintComponent" method: * * class MyPanel extends JPanel { * // override the paintComponent method * public void paintComponent(Graphics g) { * super.paintComponent(g); // calls the default method first! * g.drawString("Hello Panel!", 75, 100); // our own renderings... * } //paintComponent * } //class MyPanel * * A JFrame has several layers, but the main one for * adding components is called "content pane". * We need to get this pane: * Container contentPane = frame.getContentPane(); * Then add various components to it. In the present * example, we add a JPanel: * contentPane.add( new MyPanel()); **/ import java.awt.*; import java.awt.event.*; import javax.swing.*; // text panel class textPanel extends JPanel { // override the paintComponent method public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("Hello Panel!", 75, 100); } //paintComponent } //class textPanel class MyFrame extends JFrame { public MyFrame(String s) { // Frame Parameters setTitle(s); setSize(300,200); // default size is 0,0 setLocation(10,200); // default is 0,0 (top left corner) // Window Listeners addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); System.exit(0); // exit is still needed after dispose()! } //windowClosing }); //addWindowLister // Add Panels Container contentPane = getContentPane(); contentPane.add(new textPanel()); contentPane.setBackground(Color.pink); } //constructor MyFrame } //class MyFrame public class MyPanel { public static void main(String[] args) { JFrame f = new MyFrame("My Hello Panel!"); f.setVisible(true); // equivalent to f.show()! } //main } //class MyPanel /* NOTES: WindowAdapter() is class that implements WindowListers with null methods for all the 7 methods of WindowListeners! It is found in java.awt.event.*. */