In this video, we will use the Frame Window and add a TextField and Three AWT Buttons in it. Then we will use the Java AWT ActionEvent to know which button is clicked by the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
package AwtDemoPkg; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.awt.Label; import java.awt.TextField; import java.awt.Button; public class FrameWindow extends Frame implements WindowListener, ActionListener { //Sample 01: Member Variables TextField txt1; Button btn1,btn2,btn3; public FrameWindow(String FrameTitle) { //Display the Frame Window super(FrameTitle); setLayout(new FlowLayout()); setSize(270, 140); setLocation(100,100); addWindowListener(this); //Sample 02: Create a Text Field and Three Buttons Label lbl = new Label("Button Example"); txt1 = new TextField(25); btn1 = new Button("Button 1"); btn2 = new Button("Button 2"); btn3 = new Button("Button 3"); //Sample 03: Add the control to Frame Window add(lbl); add(txt1); add(btn1); add(btn2); add(btn3); //Sample 04: Register the Button with ActionListener btn1.addActionListener(this); btn2.addActionListener(this); btn3.addActionListener(this); } public void windowOpened(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowClosing(WindowEvent e) { this.dispose(); } @Override public void actionPerformed(ActionEvent e) { //Sample 05: Find who produced this ActionEvent Button eventSource = (Button) e.getSource(); if (eventSource == btn1) txt1.setText("Button 1 Clicked"); if (eventSource == btn2) txt1.setText("Button 2 Clicked"); if (eventSource == btn3) txt1.setText("Button 3 Clicked"); } } |
Categories: AWT-Tube