I am writing a program using the AWT package in which I also implemented ActionListner which shows the number of clicks I made on the button.
package awtlistenerdemo;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo implements ActionListener {
TextField t1 = new TextField(30);
Button b;
int count = 0;
Frame f;
AwtListenerDemo() {
f = new Frame("Action Listener Example");
b = new Button("Ok");
f.setLayout(null);
b.setBounds(100, 100, 60, 20);
t1.setBounds(100, 200, 80, 30);
f.add(b);
f.add(t1);
b.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b) {
count++;
t1.setText("Button Clicked" + count + "Times");
}
}
public static void main(String[] args) {
Frame f = new Frame("Action Listener Example");
f.setVisible(true);
f.setSize(300, 300);
}
}
The main
method never constructs an AwtListenerDemo
so all you see is the standard, blank frame created in that method. Once that problem is fixed, some of the statements in the main method need to be moved into the constructor and applied to the frame it creates.
This is the result:
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo implements ActionListener {
TextField t1 = new TextField(30);
Button b;
int count = 0;
Frame f;
AwtListenerDemo() {
f = new Frame("Action Listener Example");
b = new Button("Ok");
f.setLayout(null);
b.setBounds(100, 100, 60, 20);
t1.setBounds(100, 200, 80, 30);
f.add(b);
f.add(t1);
b.addActionListener(this);
// ADD this!
f.setSize(300,300);
// then set it VISIBLE
f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b) {
count++;
t1.setText("Button Clicked" + count + "Times");
}
}
public static void main(String[] args) {
// Change the main code to..
new AwtListenerDemo();
}
}
General Tips