public class DisplayMessage
1: //DisplayMessage.java
2: //From "Java Foundation Classes in a Nutshell" by David Flanagan.
3: //Provides a Yes/No Swing graphical interface for a batch file.
5: import java.awt.*; //AWT classes
6: import javax.swing.*; //Swing components and classes
7: import javax.swing.border.*; //Borders for Swing components
8: import java.awt.event.*; //Basic event handling
10: public class DisplayMessage
11: {
12: public static void main(String[] args)
13: {
14: //Create components
15: JLabel msgLabel = new JLabel(); //Displays the question
16: JButton yesButton = new JButton(); //Affirmative response
17: JButton noButton = new JButton(); //Negative response
19: //Set properties of components
20: msgLabel.setText(args[0]); //The msg to display
21: msgLabel.setBorder(new EmptyBorder(10,10,10,10)); //10-pixel mrgn
22: yesButton.setText((args.length >= 2)?args[1]:"Yes"); //Yes button
23: noButton.setText((args.length >= 3)?args[2]:"No"); //No button
25: //Create containers to hold components
26: JFrame win = new JFrame("Message"); //The main application window
27: JPanel buttonbox = new JPanel(); //A container for two buttons
28:
29: //Specify LayoutManagers to arrange components in containers
30: win.getContentPane().setLayout(new BorderLayout()); //on borders
31: buttonbox.setLayout(new FlowLayout()); //left-to-right
33: //Add components to containers, with optional layout constraints
34: buttonbox.add(yesButton); //Add yes button to panel
35: buttonbox.add(noButton); //Add no button to panel
36: //Add JLabel to window, telling BorderLayout to put it in middle
37: win.getContentPane().add(msgLabel, "Center");
38: //Add panel to window, telling BorderLayout to put it at bottom
39: win.getContentPane().add(buttonbox, "South");
40:
41: //Arrange to handle events in user interface.
42: yesButton.addActionListener(new ActionListener()
43: { //Note: inner class
44: //This method is called when Yes button is clicked.
45: public void actionPerformed(ActionEvent e) { System.exit(0); }
46: }
47: );
48: noButton.addActionListener(new ActionListener()
49: { //Note: inner class
50: //This method is called when No button is clicked.
51: public void actionPerformed(ActionEvent e) { System.exit(1); }
52: }
53: );
55: //Display GUI to user
56: win.pack(); //Set size of window based its children's sizes.
57: win.show(); //Make window visible.
58: }
59: }