我正在使用Head First Java中详细介绍的double actionlistener练习,并了解内部类,但由于某些原因,我的代码没有编译。当我尝试为JButton调用addActionListener方法时,我得到参数无效错误。
TwoButtons.java:
import javax.swing.*;
import java.awt.*;
public class TwoButtons {
JFrame frame;
JLabel label;
public static void main(String[] args){
TwoButtons gui = new TwoButtons();
gui.go();
}
public void go(){
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton labelButton = new JButton("Change Label");
labelButton.addActionListener(new LabelListener());
JButton colorButton = new JButton("Change circle");
colorButton.addActionListener(new ColorListener());
label = new JLabel("I'm a label");
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.getContentPane().add(BorderLayout.EAST, labelButton);
frame.getContentPane().add(BorderLayout.WEST, label);
frame.setSize(300,300);
frame.setVisible(true);
}
class LabelListener implements ActionListener{
public void actionPerformed(ActionEvent event){
label.setText("OUch!");
}
}//close inner class
class ColorListener implements ActionListener{
public void actionPerformed(ActionEvent event){
frame.repaint();
}
} //close inner class
}
MyDrawPanel.java :(没有错误)
import java.awt.*;
import javax.swing.*;
public class MyDrawPanel extends JPanel{
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D) g;
int red = (int)(Math.random()*255);
int green = (int)(Math.random()*255);
int blue = (int)(Math.random() * 255);
Color startColor = new Color(red,green,blue);
red = (int)(Math.random()*255);
green = (int)(Math.random()*255);
blue = (int)(Math.random() * 255);
Color endColor = new Color(red, green, blue);
GradientPaint gradient = new GradientPaint(70,70, startColor, 150,150, endColor);
g2d.setPaint(gradient);
g2d.fillOval(70, 70, 100, 100);
}
}
答案 0 :(得分:2)
您需要导入ActionEvent
和ActionListener
:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
它们位于java.awt.event.*
而不是java.awt.*
。
如果您使用像Eclipse这样的IDE,您可以通过简单的操作轻松导入所有需要的类。