伙计们,我打算实现一个简单的按钮ActionListener,但它看起来不起作用。 java代码附加如下..... 该程序打算响应用户的点击操作并更改JLabel的上下文
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Frame extends JFrame implements ActionListener {
public JButton btn = new JButton("Click");
public JLabel display = new JLabel("null");
public JPanel mainPanel = new JPanel();
public Frame() {
mainPanel.add(btn);
mainPanel.add(display);
add(mainPanel);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn) {
display.setText("it works");
System.out.println("it works");
}
}
public static void main(String[] args) {
Frame testFrame = new Frame();
testFrame.pack();
testFrame.setVisible(true);
}
}
答案 0 :(得分:7)
您的actionlistener(JFrame本身)未添加addActionListener。
答案 1 :(得分:7)
您应该将ActionListener添加到按钮
public Frame(){
mainPanel.add(btn);
mainPanel.add(display);
btn.addActionListener(this);
add(mainPanel);
}