Creating a GUI program in Java requires at least three types of objects:
* Component
* Events
* Listener
Pushcounter is a startup class and only displays a button (marked as "Push me !"), Press the button to update the counter to display the latest results.
// Pushcounter. Java
// Demonstrate a graphical user interface and listener
Import javax. Swing. jframe;
Public class pushcounter {
// Create a presentation framework
Public static void main (string [] ARGs ){
Jframe frame = new jframe ("Push counter ");
Frame. setdefaclocloseoperation (jframe. exit_on_close );
Pushcounterpanel Panel = new pushcounterpanel ();
Frame. getcontentpane (). Add (panel );
// The pack method is used to set the frame size according to the content in the frame.
Frame. Pack ();
Frame. setvisible (true );
}
}
// Pushcounterpanel. Java
Import java. AWT. color;
Import java. AWT. dimension;
Import java. AWT. event. actionevent;
Import java. AWT. event. actionlistener;
Import javax. Swing. jbutton;
Import javax. Swing. jlabel;
Import javax. Swing. jpanel;
Public class pushcounterpanel extends jpanel {
Private int count;
Private jbutton push;
Private jlabel label;
Public pushcounterpanel (){
Count = 0;
Push = new jbutton ("push me! ");
Push. addactionlistener (New buttonlistener ());
Label = new jlabel ("pushes:" + count );
Add (push );
Add (Label );
Setbackground (color. Cyan );
Setpreferredsize (new dimension (300, 40 ));
}
// Update the tag when the button is pressed.
Private class buttonlistener implements actionlistener {
Public void actionreceivmed (actionevent arg0 ){
Count ++;
Label. settext ("pushes:" + count );
}
}
}
Components used in this program include: a button, a tag for displaying the count, a panel for holding the buttons and labels, and a frame for displaying the panel.
Jframe is like a building, a panel is like a room, and things are placed in the room
Graphical things have a special attraction. After all, they are real things that can be seen.