下列程序代码是否能通过编译,如果有问题,需要修改哪里? import javax.swing.*; import java.awt.*; import java.awt.event.*; class InnerButton{ JFrame frame; JButton b; public static void main(String[] args){ InnerButton gui = new InnerButton(); gui.go(); } public void go(){ frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); b = new JButton("A"); b.addActionListener(); frame.getContentPane().add(BorderLayout.SOUTH,b); frame.setSize(200,100); frame.setVisible(true); } class BListener extends ActionListener{ public void actionPerformed(ActionEvent e){ if(b.getText().equals("A")){ b.setText("B"); } else{ b.setText("A"); } } } }
时间: 2024-03-07 17:47:09 浏览: 57
这段代码无法通过编译。需要在 b.addActionListener() 方法中传入一个 ActionListener 对象,但是当前代码中没有传入任何对象。需要将该方法修改为 b.addActionListener(new BListener())。同时,BListener 类需要在 InnerButton 类的内部进行定义。修改后的代码如下:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class InnerButton {
JFrame frame;
JButton b;
public static void main(String[] args) {
InnerButton gui = new InnerButton();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b = new JButton("A");
b.addActionListener(new BListener());
frame.getContentPane().add(BorderLayout.SOUTH, b);
frame.setSize(200, 100);
frame.setVisible(true);
}
class BListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (b.getText().equals("A")) {
b.setText("B");
} else {
b.setText("A");
}
}
}
}
```
阅读全文