0

スタックから作成されたボタンのグループをリッスンするアクション コマンド/アクションをプログラムに割り当てる方法に頭を悩ませています。ボタンは、テキスト ファイルの行から作成されます。

public void getLaunchButtons(){


    File list = new File("resources/programs.txt");

    String line = null;

    try{

        FileReader fr = new FileReader(list);
        BufferedReader br = new BufferedReader(fr);

        buttons = new Stack<Button>();

        while((line = br.readLine()) != null){
        buttons.push(new Button(line));
        add(buttons.pop());

        }

        br.close();

    }
    catch(Exception ex){

    }
}

作成したボタンにアクション リスナーを割り当てるにはどうすればよいですか? 私の全体的な目標は、クリックするとそのボタンに関連付けられたプログラムを起動するボタンを作成することです。ユーザーは、プログラム タイトル (ボタン タイトル) とディレクトリを起動するプログラム (ボタン アクション コマンド) に追加できます。

4

2 に答える 2

0

これを試してください

Button b = new Button(line);
b.addActionListener(listener);
add(b);

//In global
ActionListener listener = new ActionListener()
{
  public void actionPerformed(ActionEvent actionEvent) {
        JButton button = (JButton)actionEvent.getSource();
        String line = button.getText();
 }
};
于 2013-10-18T18:27:51.700 に答える
0

非常に基本的なことです。ボタンをスタックに直接貼り付けようとするのではなく、ボタンへの参照を取得します。

Button b = new Button(line);
b.addActionListener(referenceToActionListener);
buttons.push(b);
add(b);
于 2013-10-18T18:20:07.593 に答える