0

タイトルが短い場合はまずお詫び申し上げます。考え直しましたが、私の質問に十分な短い要約を思い付くことができません。

JButtonで構成されるJPanelクラスがあります。

JPanel クラスと同様に、Swing コンポーネントを持つメインの Swing アプリケーション クラスがあります。私がやりたいことは、JPanel クラスから起動された ActionEvents が Swing アプリケーション クラスにディスパッチされて処理されるようにすることです。ネットやフォーラム (これを含む) で例を検索しましたが、うまく動作しないようです。

私のJPanelクラス:

public class NumericKB extends javax.swing.JPanel implements ActionListener {
    ...

    private void init() {
        ...
        JButton aButton = new JButton();
        aButton.addActionListener(this);

        JPanel aPanel= new JPanel();
        aPanel.add(aButton);
        ...
    }

    ...

    @Override
    public void actionPerformed(ActionEvent e) {   
        Component source = (Component) e.getSource();

        // recursively find the root Component in my main app class
        while (source.getParent() != null) {            
            source = source.getParent();
        }

        // once found, call the dispatch the current event to the root component
        source.dispatchEvent(e);
    }

    ...
}



私の主なアプリクラス:

public class SimplePOS extends javax.swing.JFrame implements ActionListener {


    private void init() {
        getContentPane().add(new NumericKB());
        pack();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        ...

        // this is where I want to receive the ActionEvent fired from my NumericKB class
        // However, nothing happens

    }
}  


別のJPanelクラスを書きたい理由は、これを他のアプリで再利用したいからです。

また、実際のコード、私のメイン アプリ クラスには多くのサブコンポーネントがあり、JPanel クラスがサブコンポーネントの 1 つに追加されているため、再帰的な .getParent() 呼び出しが行われます。

どんな助けでも大歓迎です。少し早いですがお礼を!乾杯。

4

1 に答える 1

1

親は の配信をサポートしていないため、イベントを親に再スローすることはできませんActionEvent。しかし、あなたの場合、コンポーネントがアクションをサポートしているかどうかを確認して呼び出すことができます。このようなもの

public class NumericKB extends javax.swing.JPanel implements ActionListener {
  ...

  private void init() {
    ...
    JButton aButton = new JButton();
    aButton.addActionListener(this);

    JPanel aPanel= new JPanel();
    aPanel.add(aButton);
    ...
  }

  ...

  @Override
  public void actionPerformed(ActionEvent e) {   
    Component source = (Component) e.getSource();

    // recursively find the root Component in my main app class
    while (source.getParent() != null) {            
        source = source.getParent();
    }

    // once found, call the dispatch the current event to the root component
    if (source instanceof ActionListener) {
      ((ActionListener) source).actionPerformed(e);
    }
  }

...
}
于 2014-06-05T15:06:12.973 に答える