2015-08-14 12 views
0

,並創建一個自定義的JButton /組件。我最什麼,我需要的,只是我不知道該怎麼稱呼的actionPerformed我ActionListners。調用在學習的過程中,我一個ActionEvent

代碼:

package myProjects; 

import java.awt.BasicStroke; 
import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Shape; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.geom.*; 
import java.util.ArrayList; 
import javax.swing.JButton; 
import javax.swing.JComponent; 
import javax.swing.JFrame; 

public class LukeButton extends JComponent{ 
    public static void main(String[] args){ 
     JFrame frame = new JFrame(); 
     frame.setTitle("Luke"); 
     frame.setSize(300, 300); 
     frame.setLocationRelativeTo(null); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     LukeButton lb = new LukeButton(); 
     lb.addActionListener(e->{ 
      System.out.println("Success"); 
     }); 
     frame.add(lb); 

     frame.setVisible(true); 
    } 

private final ArrayList<ActionListener> listeners = new ArrayList<ActionListener>(); 

public LukeButton(){ 

} 
public void addActionListener(ActionListener e){ 
    listeners.add(e); 
} 
public void paintComponent(Graphics g){ 

    super.paintComponent(g); 

    Graphics2D g2 = (Graphics2D)g; 
    Shape rec = new Rectangle2D.Float(10, 10, 60, 80); 

    g2.setColor(Color.BLACK); 
    g2.setStroke(new BasicStroke(5)); 
    g2.draw(rec); 
    g2.setColor(Color.BLUE); 
    g2.fill(rec); 
} 
} 

有誰一個知道如何調用「聽衆」的ArrayList一旦按鈕被點擊?感謝您抽出時間。

回答

3

你需要循環在你的ActionListener S和列表調用它們actionPerformed方法,像...

protected void fireActionPerformed() { 
    if (!listeners.isEmpty()) { 

     ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "LukeButton"); 
     for (ActionListener listener : listeners) { 
      listener.actionPerformed(evt); 
     } 

    } 
} 

現在,您需要定義這可能會引發ActionEvent要發生的動作,鼠標點擊,按鍵等,並呼叫,當他們發生

看一看How to Write a Mouse ListenerHow to Use Key Bindings更多細節

+0

感謝fireActionPerformed方法,幫助很大,I L贏得新的東西:) –