package zaehlerbeispiel;

import java.awt.Button;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author  Ralf Kunze (rkunze@uos.de), Institut fuer Informatik, Universitaet Osnabrueck
 * @date 19.06.2007
 */
public class GUI {

    private Label infoLabel;
    private TextField zaehlerTF;
    private Button incrementBto;
    private Frame frame;
    private Dialog endProgramDialog;
    
    public void createGUI(int initialValue) {
        frame = new Frame("Counter-Beispiel");
        frame.setLayout(new GridLayout(0,1));
        
        createEndProgramDialog();
        
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
               endProgramDialog.setVisible(true); 
            }
        });
        
        infoLabel = new Label("Beispiel fuer Eventverarbeitung");
        frame.add(infoLabel);
        
        zaehlerTF = new TextField("" + initialValue, 10);
        zaehlerTF.setEditable(false);
        frame.add(zaehlerTF);
        
        incrementBto = new Button("Erhoehen");
        incrementBto.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                int value = Integer.parseInt(zaehlerTF.getText());
                value++;
                zaehlerTF.setText("" + value);
            }
            
        });
        
        frame.add(incrementBto);
        
        frame.pack();
        frame.setVisible(true);
    }
   
    private void createEndProgramDialog() {
        endProgramDialog = new Dialog(frame, "Programm verlassen?", true);
        endProgramDialog.setLayout(new GridLayout(0,1));
        
        
        endProgramDialog.add(new Label("Wollen Sie das Programm wirklich verlassen?"));
        Button okBto = new Button("OK");
        Button cancelBto = new Button("Cancel");
        
        okBto.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        
        cancelBto.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                endProgramDialog.setVisible(false);
            }
        });
        
        endProgramDialog.add(okBto);
        endProgramDialog.add(cancelBto);
        
        endProgramDialog.pack();
    }
    
    
    public static void main(String[] args) {
        new GUI().createGUI(42);
    }

}
