[英]I am writing a program using awt pakage in java but my components are not getting added
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.我正在使用 AWT 包编写一个程序,其中我还实现了 ActionListner,它显示了我在按钮上的点击次数。
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);
}
}
TextField t1 = new TextField(30);
Button b;
int count = 0;
Frame f;
AwtListenerDemo() {
b = new Button("Ok");
f = new Frame("Action Listener Example");
f.setSize(300, 300);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setLayout(null);
b.setBounds(100, 100, 60, 20);
t1.setBounds(100, 200, 80, 30);
f.add(b);
f.add(t1);
f.setVisible(true);
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) {
new AwtListenerDemo();
}
The main
method never constructs an AwtListenerDemo
so all you see is the standard, blank frame created in that method. main
方法从不构造AwtListenerDemo
因此您看到的只是在该方法中创建的标准空白帧。 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.一旦这个问题得到解决,main 方法中的一些语句需要移到构造函数中并应用于它创建的框架。
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一般提示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.