/*
Creating GUI with JLabel and JButton
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class GUITextFieldLabelAndButtons extends JFrame implements ActionListener
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private static final int BUTTON_WIDTH = 80;
private static final int BUTTON_HEIGHT = 30;
//Declare your objects here...
private JButton cancelButton; // Declare the buttons
private JButton okButton;
private JLabel promptText1; // Declare text
private JTextField inputLine; //This part added for Input Text field
public static void main(String[] args)
{
GUITextFieldLabelAndButtons frame = new GUITextFieldLabelAndButtons();
frame.setVisible(true); // Display the frame
}
public GUITextFieldLabelAndButtons( )
{
// set the frame properties
setTitle("Sample Frame with Button Events");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setResizable(false);
// set the content pane properties
Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.setBackground(Color.white);
//create and place two buttons on the frame's content pane
okButton = new JButton("Ok");
okButton.setBounds(70, 125, BUTTON_WIDTH, BUTTON_HEIGHT);
okButton.addActionListener(this);
contentPane.add(okButton);
cancelButton = new JButton("Cancel");
cancelButton.setBounds(160,125, BUTTON_WIDTH, BUTTON_HEIGHT);
cancelButton.addActionListener(this);
contentPane.add(cancelButton);
promptText1 = new JLabel();
promptText1.setText("Display some text here");
promptText1.setBounds(30, 20, 150, 25); // 30 from left, 20 from top, 150 length, 25 height
promptText1.setForeground(Color.red);
contentPane.add(promptText1);
inputLine = new JTextField();
inputLine.setBounds(30, 50, 150, 25);
contentPane.add(inputLine);
inputLine.addActionListener(this);
// register 'Exit' upon closing as default close operation
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event) // Actions
{
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
String somethingYouEntered = inputLine.getText();
if (clickedButton == okButton) // Event when ok button is clicked
{
JOptionPane.showMessageDialog(null, "You clicked on OK");
JOptionPane.showMessageDialog(null, "and you also entered: " + somethingYouEntered);
}
if (clickedButton == cancelButton) // Event when cancel button is clicked
{
JOptionPane.showMessageDialog(null, "You clicked on Cancel");
JOptionPane.showMessageDialog(null, "Bye bye!");
System.exit(0);
}
}
} // End of class