0
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
class Painter extends JPanel implements ActionListener{
private int x = 30, y = 30;
//remove the blocked comment to make it run
/*public Painter(){
Buttons b = new Buttons(new String("Click to paint"));
b.addActionListener(this);
add(b);
}*/
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(new Color(44,55,66));
g.fillRect(200,200,x,y);
}
public void actionPerformed(ActionEvent e){
x = 600;
y = 600;
repaint();
}
}
import javax.swing.JButton;
public class Buttons extends JButton{
public Buttons(String Tag){
super(Tag);
setBounds(20, 20, 150, 50);
Painter p = new Painter();//comment it out
addActionListener(p);//comment it out
}
}
import java.awt.Color;
import javax.swing.JFrame;
public class Window extends JFrame{
public Window(){
Buttons b = new Buttons("Click Me");//comment it out
Painter p = new Painter();
getContentPane().add(b);//comment it out
getContentPane().add(p);
getContentPane().setBackground(Color.WHITE);
setSize(700,700);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
public class PaintOnEvent {
public static void main(String[] args){
Window w = new Window();
}
}
這是一個測試程序。我使用addActionListener()
方法將Painter
類註冊到Buttons類,那麼爲什麼它仍不能查找actionperformed
方法?然後當我在畫家類中創建一個按鈕時,它就起作用了。爲什麼這樣?Button無法找到Listener類
你是對的,它其實是兩個畫家的例子。但是,當我像你說的那樣做時,按鈕會頻繁顯示。是否因爲按鈕和麪板分別添加到窗口中? – Gopal 2011-02-07 03:12:56