[Work/Class/Java with Processing/4_SwingInProcessing]

アート系学生のためのJAVA with Processing - その4-3 ActionCommandで複数のボタンを作りイベントを制御する

導入

複数のボタンを使って制御する内容を変えたい場合は,setActionCommandで別々のActionCommandを割り当て,それをactionPerformed関数内やactionPerformedから呼び出す関数内で振り分けて,処理を記述すれば良い.

コード

//SwingInProcessing_MultipleButtons

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

// macOSのJavaのProcessing最新版はこれでうまくいかないこともあるので
// processing.awt.PSurfaceAWT.SmoothCanvas;
// も追加

void setup(){
  size(640, 480);
  Canvas canvas = (Canvas)surface.getNative();
  // macOSのJavaのProcessing最新版はこれでうまくいかないこともあるので
  // SmoothCanvas canvas = (SmoothCanvas)getSurface().getNative();
  // で置き換える

  JLayeredPane layeredPane = 
    (JLayeredPane)canvas.getParent().getParent();

  JTextField textField = new JTextField("New Text Field");
  textField.setBounds(10, 360, 620, 20);
  
  MyButtonListener myButtonListener = 
    new MyButtonListener();
  myButtonListener.setTextField(textField);
  
  JButton button1 = new JButton("Button 1");
  button1.setBounds(10, 390, 100, 20);
  button1.setActionCommand("button1_push");
  button1.addActionListener(myButtonListener);
  
  // Add more one button named button2
  // ActionCommandを変えてボタンをもう一個作る.
  JButton button2 = new JButton("Button 2");
  // ボタンの表示位置はずらす
  button2.setBounds(120, 390, 100, 20);
  button2.setActionCommand("button2_push");
  // 登録するActionListenerを実装したクラスオブジェクトは同じもので良い
  // 内部でActionCommandを使って処理を切り分けるため
  button2.addActionListener(myButtonListener);
  
  layeredPane.add(textField);
  layeredPane.add(button1);
  // 2個目のボタンも表示画面に登録する
  layeredPane.add(button2);
}

void draw(){
  ellipse(0, 0, 100, 100);
}

class MyButtonListener implements ActionListener {
  JTextField textField;
  
  void setTextField(JTextField textField){
    this.textField = textField;
  }
  
  @Override
  public void actionPerformed(ActionEvent e){
    String actionCommand = e.getActionCommand();
    if(actionCommand.equals("button1_push")){
      textField.setText("Button1 has been pushed");
    }
    else if(actionCommand.equals("button2_push")){
      // ボタン2の時の処理内容.表示するテキストを変えている.
      textField.setText("Button2 has been pushed");
    }
  }
}
SwingInProcessing_MutipleButtons.pdeの実行結果の初期状態.テキストフィールドに初期状態のテキストが入っている.

初期状態では,テキストフィールドに表示されているのは初期状態のテキスト.

SwingInProcessing_MutipleButtons.pdeでButton1を押した結果.テキストフィールドにButton1のアクションコマンドで振り分けられた処理の結果が挿入されている.

Button1を押すと,設定されたアクションコマンド「button1_push」が入ったActionEventが渡されるので,String.equals()で判別し(Stringの詳しい内容は次項),その後の処理で書かれたTextField.setText()で入力した文字列が表示される.

SwingInProcessing_MutipleButtons.pdeでButton2を押した結果.テキストフィールドにButton2のアクションコマンドで振り分けられた処理の結果が挿入されている.

Button2を押すと,同様にButton2設定されたアクションコマンド「button2_push」が入ったActionEventが渡される