2012-05-06 4 views
2

下記の過度に単純化された例を考えてみましょう。簡潔にするために疑似コードで書かれたものもあります。これをそのまま実行しようとすると、私のmainメソッドですでに見つかったactionPerformedというコンパイラエラーが発生します。ただし、名前を変更した場合、actionPerformed2と認識されなくなりました。ActionListenerによって認識されなくなりました。1つのクラスで複数のActionListenersを使用できますか?

foofoo2の両方のメソッドのリスナーを、単一のActionListenerメソッドに組み合わせる必要がありますか?複数のボタンオブジェクトを持つ単一のクラスで複数のリスナーを使用する場合、リスナーを適切に区別するにはどうすればよいですか?

私はちょうどスイングコンポーネントで遊んでいますので、正しい質問をしていない可能性がありますが、私はいつも編集しています。 :)

public class foo { 
    declare button1, button2, button3 and panel1 
    public foo() { 
     show panel1 with button1 and button2; 
    } 
    public foo2() { 
     show panel1 with button3; 
    } 
    public void actionPerformed(ActionEvent e) { 
     Object source1 = e.getSource(); 
     do some stuff when button1 is clicked 
    } 
    public void actionPerformed(ActionEvent f) { 
     Object source2 = f.getSource(); 
     do some other stuff when button2 is clicked 
    } 
    public static void main(String[] args) { 
     foo myFoo = new foo(); 
    } 
} 
+0

示されていません。同じシグネチャを持つ複数のメソッドがあります。合法ではありません。ホバークラフトは言うとおり、匿名の内部クラスは一つの答えです。 –

答えて

10

匿名の内部クラスを使用します。例えば

、あなたが書いたことはないコードが、それはポイントを示しています

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.*; 

public class Foo extends JPanel { 
    private JButton btnA = new JButton("Button A"); 
    private JButton btnB = new JButton("Button B"); 
    private JButton btnC = new JButton("Button C"); 

    public Foo() { 
     btnA.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent arg0) { 
      System.out.println("button A Action"); 
     } 
     }); 
     btnB.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent arg0) { 
      System.out.println("button B Action"); 
     } 
     }); 
     btnC.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent arg0) { 
      System.out.println("button C Action"); 
     } 
     }); 

     add(btnA); 
     add(btnB); 
     add(btnC); 
    } 

    private static void createAndShowGui() { 
     Foo mainPanel = new Foo(); 

     JFrame frame = new JFrame("Foo"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 

私自身、私はより多くのAbstractActionsと少ないたActionListenerには使用しています、とさえこの中のコマンドデザインパターンを使用して開始していますPropertyChangeListenerとのコンサート一例として、

は、私の最新のGUIの「ビュー」セクションには、次のようになります。

import java.awt.BorderLayout; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.KeyEvent; 
import java.beans.PropertyChangeListener; 
import java.util.HashMap; 
import java.util.Map; 

import javax.swing.*; 
import javax.swing.event.SwingPropertyChangeSupport; 

@SuppressWarnings("serial") 
public class View { 
    enum TextAreaDestination { 
     EGD_IMPRESSION("EGD Impression"), 
     EGD_RECOMMENDATIONS("EGD Recommendations"), 
     COLON_IMPRESSION("Colon Impression"), 
     COLON_RECOMMENDATIONS("Colon Recommendations"), 
     ERROR_MESSAGES("Error Messages"); 

     private String text; 
     private TextAreaDestination(String text) { 
     this.text = text; 
     } 

     public String getText() { 
     return text; 
     } 

     @Override 
     public String toString() { 
     return text; 
     } 
    } 

    public enum GuiButtonText { 
     GET_ONE_PROC("Get One Proc", KeyEvent.VK_O), 
     GET_TWO_PROCs("Get Two Procs", KeyEvent.VK_T), 
     INTO_FLOW("Into Flow", KeyEvent.VK_F), 
     CLEAR_ALL("Clear All", KeyEvent.VK_C), 
     F_U_PROC_FLAG("F/U Proc Flag", KeyEvent.VK_U), 
     SIGN_NEXT("Sign/Next", KeyEvent.VK_S), 
     EXIT("Exit", KeyEvent.VK_X); 
     private String text; 
     private int mnemonic; 
     private GuiButtonText(String text, int mnemonic) { 
     this.text = text; 
     this.mnemonic = mnemonic; 
     } 
     public String getText() { 
     return text; 
     } 
     public int getMnemonic() { 
     return mnemonic; 
     } 
    } 

    public static final String BUTTON_PRESSED = "Button Pressed"; 

    private static final int TA_ROWS = 4; 
    private static final int TA_COLS = 50; 
    private JPanel mainPanel = new JPanel(); 
    private SwingPropertyChangeSupport spcSupport = new SwingPropertyChangeSupport(
     this); 
    private Map<TextAreaDestination, JTextArea> impressionRecMap = new HashMap<TextAreaDestination, JTextArea>(); 

    public View() { 
     JPanel textAreasPanel = createTextAreasPanel(); 
     JPanel buttonsPanel = createButtonsPanel(); 

     mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); 
     mainPanel.setLayout(new BorderLayout(5, 5)); 
     mainPanel.add(textAreasPanel, BorderLayout.CENTER); 
     mainPanel.add(buttonsPanel, BorderLayout.PAGE_END); 
    } 

    private JPanel createButtonsPanel() { 
     JPanel buttonsPanel = new JPanel(new GridLayout(2, 0, 5, 5)); 
     for (final GuiButtonText guiBtnText : GuiButtonText.values()) { 
     AbstractAction btnAction = new AbstractAction(guiBtnText.getText()) { 
      {putValue(MNEMONIC_KEY, guiBtnText.getMnemonic()); } 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       spcSupport.firePropertyChange(BUTTON_PRESSED, null, guiBtnText);    
      } 
     }; 
     JButton button = new JButton(btnAction); 
     buttonsPanel.add(button); 
     } 
     return buttonsPanel; 
    } 

    private JPanel createTextAreasPanel() { 
     JPanel textAreasPanel = new JPanel(); 
     textAreasPanel.setLayout(new BoxLayout(textAreasPanel, 
      BoxLayout.PAGE_AXIS)); 
     for (TextAreaDestination textDest : TextAreaDestination.values()) { 
     JTextArea tArea = new JTextArea(TA_ROWS, TA_COLS); 
     tArea.setName(textDest.getText()); 
     tArea.setWrapStyleWord(true); 
     tArea.setLineWrap(true); 
     impressionRecMap.put(textDest, tArea); 
     JScrollPane scrollPane = new JScrollPane(tArea); 
     JPanel outerPanel = new JPanel(new BorderLayout()); 
     outerPanel.setBorder(BorderFactory.createTitledBorder(textDest.getText())); 
     outerPanel.add(scrollPane); 
     textAreasPanel.add(outerPanel); 
     } 
     return textAreasPanel; 
    } 

    public String textAreasGetText(TextAreaDestination key) { 
     JTextArea textArea = impressionRecMap.get(key); 
     if (textArea != null) { 
     return textArea.getText(); 
     } else { 
     return ""; // throw exception 
     } 
    } 

    public void textAreasSetText(TextAreaDestination key, String text) { 
     JTextArea textArea = impressionRecMap.get(key); 
     if (textArea != null) { 
     textArea.setText(text); 
     } else { 
     // throw exception? 
     } 
    } 

    public void textAreaAppend(TextAreaDestination key, String text) { 
     JTextArea textArea = impressionRecMap.get(key); 
     textArea.append(text); 
    } 

    public void clearAllAreas() { 
     for (TextAreaDestination taDest : TextAreaDestination.values()) { 
     textAreasSetText(taDest, ""); 
     } 
    } 

    public void addPropertyChangeListener(PropertyChangeListener listener) { 
     spcSupport.addPropertyChangeListener(listener); 
    } 

    public void removePropertyChangeListener(PropertyChangeListener listener) { 
     spcSupport.removePropertyChangeListener(listener); 
    } 

    public JPanel getMainPanel() { 
     return mainPanel; 
    } 

    public static void main(String[] args) { 
     Control.main(args); 
    } 
} 

そして、「コントロール」セクションの部分はそうのようになります。

import java.awt.Component; 
import java.awt.Window; 
import java.beans.PropertyChangeEvent; 
import java.beans.PropertyChangeListener; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
import java.util.concurrent.ExecutionException; 
import javax.swing.*; 
import procedure.findings4.View.TextAreaDestination; 

public class Control { 
    public static final boolean DEBUG = false; 

    public static final String CENTRICITY_WINDOW_NAME = "Centricity EMR"; 
    private DriverModel driverModel = null; 
    private View view; 
    private Map<View.GuiButtonText, Runnable> runnableMap = new HashMap<View.GuiButtonText, Runnable>(); 

    public Control() { 
     runnableMap.put(View.GuiButtonText.GET_ONE_PROC, new GetOneProcRunnable()); 
     runnableMap.put(View.GuiButtonText.GET_TWO_PROCs, 
      new GetTwoProcsRunnable()); 
     runnableMap.put(View.GuiButtonText.INTO_FLOW, new IntoFlowRunnable()); 
     runnableMap.put(View.GuiButtonText.CLEAR_ALL, new ClearAllRunnable()); 
     runnableMap.put(View.GuiButtonText.SIGN_NEXT, new SignNextRunnable()); 
     runnableMap.put(View.GuiButtonText.EXIT, new ExitRunnable()); 
    } 

    public void setView(View view) { 
     this.view = view; 
     view.addPropertyChangeListener(new ViewChangeListener()); 
    } 

    //.... 

    private class ViewChangeListener implements PropertyChangeListener { 
     @Override 
     public void propertyChange(PropertyChangeEvent pcEvt) { 
     if (pcEvt.getPropertyName().equals(View.BUTTON_PRESSED)) { 
      Runnable run = runnableMap.get(pcEvt.getNewValue()); 
      if (run != null) { 
       run.run(); 
      } 
     } 
     } 
    } 

    //.... 

なお、Iドンこれで専門家であると主張するのではなく、可能な限り複雑さを管理しようとしています。おそらく、この猫を肌に触れる良い方法があります。

関連する問題