MessageBox class implemented in Java

Source: Internet
Author: User

The MessageBox class prompts the Java application warning and error.

Package com. Nova. colimas. Install;

Import java. AWT. event. actionevent;
Import java. AWT. event. actionlistener;
Import java. AWT. event. keyevent;
Import java. AWT. event. keylistener;
Import java. AWT. event. javaswevent;
Import java. AWT. event. windowlistener;
Import javax. Swing .*;
Import java. AWT .*;

Public class MessageBox implements runnable, actionlistener, windowlistener,
Keylistener {

// ---------- Private fields ------------------------------
Private actionlistener listener;

Private jdialog dialog;

Private string closewindowcommand = "closerequested ";

Private String title;

Private jframe;

Private Boolean framenotprovided;

Private jpanel buttonpanel = new jpanel ();

// ---------- Initialization ------------------------------
/**
* This convenience constructor is used to delare the listener that will be
* Notified when a button is clicked. the listener must implement
* Actionlistener.
*/
Public MessageBox (actionlistener listener ){
This ();
This. Listener = listener;
}

/**
* This constructor is used for no listener, such as for a simple okay
* Dialog.
*/
Public MessageBox (){
}

// Unit test. Shows only simple features.
Public static void main (string ARGs []) {
MessageBox box = new MessageBox ();
Box. settitle ("test MessageBox ");
Box. askyesno ("Tell me now./Ndo you like Java? ");
}

// ---------- Runnable implementation ---------------------
/**
* This prevents the caller from blocking on ASK (), which if this class is
* Used on an AWT event thread wocould cause a deadlock.
*/
Public void run (){
Dialog. setvisible (true );
}

// ---------- Actionlistener implementation ---------------
Public void actionreceivmed (actionevent EVT ){
Dialog. setvisible (false );
Dialog. Dispose ();
If (framenotprovided)
Frame. Dispose ();
If (listener! = NULL ){
Listener. actionreceivmed (EVT );
}
}

// ---------- Windowlistener implementatons ---------------
Public void windowclosing (incluwevent EVT ){
// User clicked on X or chose close Selection
Firecloserequested ();
}

Public void windowclosed (incluwevent EVT ){
}

Public void windowdeiconified (incluwevent EVT ){
}

Public void incluwiconified (incluwevent EVT ){
}

Public void windowopened (incluwevent EVT ){
}

Public void windowactivated (receivwevent EVT ){
}

Public void windowdeactivated (receivwevent EVT ){
}

// ---------- Keylistener implementation ------------------
Public void keytyped (keyevent EVT ){
}

Public void keypressed (keyevent EVT ){
If (EVT. getkeycode () = keyevent. vk_escape ){
Firecloserequested ();
}
}

Public void keyreleased (keyevent EVT ){
}

Private void firecloserequested (){
Actionevent event = new actionevent (this, actionevent. action_receivmed,
Closewindowcommand );
Actionreceivmed (event );
}

// ---------- Public methods ------------------------------
/**
* This set the listener to be notified of Button clicks and windowclosing
* Events.
*/
Public void setactionlistener (actionlistener listener ){
This. Listener = listener;
}

Public void settitle (String title ){
This. Title = title;
}

/**
* If a frame is provided then it is used to instantiate the modal dialog.
* Otherwise a temporary frame is used. Providing a frame will have
* Effect of putting the focus back on that frame when the MessageBox is
* Closed or a button is clicked.
*/
Public void setframe (jframe frame) {// optional
This. Frame = frame;
}

/**
* Sets the actioncommand used in the actionevent when the user attempts
* Close the window. The window may be closed by clicking on "X", choosing
* Close from the window menu, or pressing the Escape key. The default
* Command is "closerequested", which is just what a close choice button
* Wocould probably have as a command.
*/
Public void setclosewindowcommand (string command ){
Closewindowcommand = command;
}

/**
*
*
* @ Param label
* Will be used for the button and
* @ Param command
* Will be returned to the listener.
*/
Public void addchoice (string label, string command ){
Jbutton button = new jbutton (Label );
Button. setactioncommand (command );
Button. addactionlistener (this );
Button. addkeylistener (this );

Buttonpanel. Add (button );
}

/**
* A convenience method that assumes the command is the same as the label.
*/
Public void addchoice (string label ){
Addchoice (Label, label );
}

/**
* One of the "Ask" methods must be the last call when using a MessageBox.
* This is the simplest "Ask" method. It presents the provided
*
* @ Param message.
*/
Public void ask (string message ){
If (frame = NULL ){
Frame = new jframe ();
Framenotprovided = true;
} Else {
Framenotprovided = false;
}
Dialog = new jdialog (frame, true); // Modal
Dialog. addwindowlistener (this );
Dialog. addkeylistener (this );
Dialog. settitle (title );
Dialog. setlayout (New borderlayout (5, 5 ));

Jpanel messagepanel = createmultilinepanel (Message );
Jpanel centerpanel = new jpanel ();
Centerpanel. Add (messagepanel );
Dialog. Add ("center", centerpanel );
Dialog. Add ("South", buttonpanel );
Dialog. Pack ();
Enforceminimumsize (dialog, 200,100 );
Centerwindow (DIALOG );
Toolkit. getdefatooltoolkit (). Beep ();

// Start a new thread to show the Dialog
Thread thread = new thread (this );
Thread. Start ();
}

/**
* Same as ASK (string message) Does T adds an "okay" button.
*/
Public void askokay (string message ){
Addchoice ("okay ");
Ask (Message );
}

/**
* Same as ASK (string message) Does T adds "yes" and "no" buttons.
*/
Public void askyesno (string message ){
Addchoice ("yes ");
Addchoice ("no ");
Ask (Message );
}

// ---------- Private methods -----------------------------
Private jpanel createmultilinepanel (string message ){
Jpanel mainpanel = new jpanel ();
Gridbaglayout gblayout = new gridbaglayout ();
Mainpanel. setlayout (gblayout );
Addmultilinestring (message, mainpanel );
Return mainpanel;
}

// There are a variaty of ways to do this ....
Private void addmultilinestring (string message, container ){

Gridbagconstraints constraints = getdefaultconstraints ();
Constraints. gridwidth = gridbagconstraints. remainder;
// Insets () ARGs are top, left, bottom, right
Constraints. insets = new insets (0, 0, 0, 0 );
Gridbaglayout gblayout = (gridbaglayout) container. getlayout ();

While (message. Length ()> 0 ){
Int newlineindex = message. indexof ('/N ');
String line;
If (newlineindex> = 0 ){
Line = message. substring (0, newlineindex );
Message = message. substring (newlineindex + 1 );
} Else {
Line = message;
Message = "";
}
Jlabel label = new jlabel (line );
Gblayout. setconstraints (Label, constraints );
Container. Add (Label );
}
}

Private gridbagconstraints getdefaultconstraints (){
Gridbagconstraints constraints = new gridbagconstraints ();
Constraints. weightx = 1.0;
Constraints. weighty = 1.0;
Constraints. gridheight = 1; // one row high
// Insets () ARGs are top, left, bottom, right
Constraints. insets = new insets (4, 4, 4, 4 );
// Fill of none means do not change size
Constraints. Fill = gridbagconstraints. None;
// West means align left
Constraints. Anchor = gridbagconstraints. West;

Return constraints;
}

Private void centerwindow (jdialog win ){
Dimension screendim = toolkit. getdefatooltoolkit (). getscreensize ();
// If larger than screen, reduce window width or height
If (screendim. width <win. getsize (). width ){
Win. setsize (screendim. Width, win. getsize (). Height );
}
If (screendim. height <win. getsize (). Height ){
Win. setsize (win. getsize (). Width, screendim. Height );
}
// Center frame, dialogue or window on screen
Int x = (screendim. Width-win. getsize (). width)/2;
Int y = (screendim. Height-win. getsize (). Height)/2;
Win. setlocation (x, y );
}

Private void enforceminimumsize (jdialog comp, int minwidth, int minheight ){
If (Comp. getsize (). width <minwidth ){
Comp. setsize (minwidth, comp. getsize (). Height );
}
If (Comp. getsize (). height <minheight ){
Comp. setsize (Comp. getsize (). Width, minheight );
}
}

} // End class

Add a close button in the windowsmain class that calls it. When you click the close button, select YES or NO when you call MessageBox.

Jclosebutton. addactionlistener (New java. AWT. event. actionlistener (){
Public void actionreceivmed (Java. AWT. event. actionevent e ){
// System. Out. println ("action=med ()"); // todo auto-generated event stub action=med ()
MessageBox box = new MessageBox ();
Box. settitle ("warning ");
Box. askyesno ("Do you really want to exit? ");

// Add the MessageBox button event listener.
Box. setactionlistener (New java. AWT. event. actionlistener (){
Public void actionreceivmed (Java. AWT. event. actionevent e ){
Jbutton button = (jbutton) E. getsource ();
If (button. gettext () = "yes ")
System. Exit (0 );
}
}
);
}
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.