Program(Important points: control, layout, and event processing)
Code Import Java. AWT. * ;
Import Java. AWT. event. * ;
Public ClassMyframeExtendsFrame {
PrivateTextfield TF;
Public static void main (string ARGs []) {
myframe fr = New myframe ( " Hello out there! " );
Fr. initui ();
}
Public myframe (string Str) {
super (STR); /// call the constructor of the parent class
}
Public VoidInitui ()
{
//Frame
//Setsize (200,200 );
Setbackground (color. Red );
// Setlayout (null );
// Setlayout (New flowlayout ());
// Setlayout (New borderlayout ()); // Bad
Setlayout ( New Gridlayout ( 2 , 3 ));
// Setlayout (New cardlayout ()); // Crash
// Setlayout (New gridbaglayout ());
//Menus
Menubar MB= NewMenubar ();
Menu M1 = New Menu ( " File " );
Menu m2 = New Menu ( " Edit " );
Menu m3 = New Menu ( " Help " );
MB. Add (M1 );
MB. Add (m2 );
MB. sethelpmenu (m3 );
Setmenubar (MB );
// controls
panel Pan = New Panel ();
pan. setsize ( 100 , 100 );
pan. setbackground (color. yellow);
Button B1= NewButton ("Button1");
B1.addactionlistener (NewButtonhandler ());
Button B2 = New Button ( " Button2 " );
B2.addactionlistener ( New Actionlistener (){
Public Void Actionreceivmed (actionevent E)
{
System. Out. println ( " Action 2 occurred " );
TF. settext ( " Action 2 occurred " );
}
});
TF = New Textfield ( 30 );
//Frames
Add (PAN );
Add (B1 );
Add (B2 );
Add (TF );
Pack ();
Addmousemotionlistener ( New Mousemotionadapter (){ // Anonymous class starts
Public Void Mousedragged (mouseevent e ){
String s = " Mouse dragging: x = " + E. getx () + " Y = " + E. Gety ();
TF. settext (s );}
}); // Anonymous class ended
Setvisible ( True );
}
}
Class Buttonhandler Implements Actionlistener {
// Only the actionevent handler can implement the actionlistener interface.
Public Void Actionreceivmed (actionevent E)
// The actionevent event object generated by the system is passed to this method as a parameter.
{
System. Out. println ( " Action occurred " );
// This interface has only one method. Therefore, when an event occurs, the system automatically calls this method.CodeWrite it in a method.
}
}
Compile and run
Javac myframe. Java
Java myframe