質問

私は内部クラスを使用して練習していますが、宿題の質問の難しさを持っています:以下のようになります:

JPanelのを拡張し、「ワン」、「二」、および「三」というラベルの付いた3つのJButtonのインスタンスを持つSwingコンポーネントクラスBetterButtonsを作成します。 BetterButtonsのコンストラクタでは、ActionListenerを実装するローカルクラスButtonListenerを書きます。このローカルクラスは、フィールドの文字列名と、それはフィールド名に割り当てる文字列パラメータを取るコンストラクタを持っています。メソッドの空隙が書かれたボタン名が押されたコンソール通知の出力をでactionPerformed。 BetterButtonsのコンストラクタでは、その行動を聞い各ボタンのためButtonListener、1の3つのインスタンスを作成します。

私はほとんど完成しています、しかし、私はラインで表現エラーの違法なスタートを切るます:

 public void actionPerformed(ActionEvent e){

ここに私のコードは次のとおりです。

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

public class BetterButtons extends JPanel {
JButton one, two, three;
JPanel p;
public BetterButtons() {
    class ButtonListener implements ActionListener {
        String name;
        *****public ButtonListener(String name) {****
                public void actionPerformed(ActionEvent e){
                    System.out.println("Button "+name+"has been pressed.");
                }
              }
          }
    one = new JButton("One");
    two = new JButton("Two");
    three = new JButton("Three");
    one.addActionListener(new ButtonListener());
    two.addActionListener(new ButtonListener());
    three.addActionListener(new ButtonListener());
    p = new JPanel();
    p.add(one);
    p.add(two);
    p.add(three);
    this.add(p);
}
  public static void main(String[] args) {
    JFrame f = new JFrame("Lab 2 Exercise 2");
    BetterButtons w = new BetterButtons();
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(w);
    f.pack();
    f.setVisible(true);
}
}

また、どのように私は、文字列変数名に割り当てられる適切な値を参照することができますか?

事前にありがとうございます。

役に立ちましたか?

解決

私はbuttonListenerのあなたの定義はすべきだと思います:

class ButtonListener implements ActionListener {
    String name;
    public ButtonListener(String name) {
            this.name = name;
     }
     public void actionPerformed(ActionEvent e){
                System.out.println("Button "+name+"has been pressed.");
     }

  }

そしてbuttonlistener、例えば、各インスタンス化に名前を渡します。

  one.addActionListener(new ButtonListener("one"));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top