Java Swing How to - Share an Action between JButton Components








Question

We would like to know how to share an Action between JButton Components.

Answer

//from ww w  .  ja v a2 s  .  c om
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;

public class Main {
  public static void main(String args[]) {
    JFrame f = new JFrame();
    Container pane = f.getContentPane();
    Icon icon = new RedOvalIcon();
    final Action action = new MyAction("Hello", icon);
    // Add tooltip
    action.putValue(Action.SHORT_DESCRIPTION, "World");
    JToolBar jt1 = new JToolBar();
    JButton b1 = new JButton(action);
    jt1.add(b1);
    pane.add(jt1, BorderLayout.NORTH);
    JToolBar jt2 = new JToolBar();
    JButton b2 = new JButton(action);
    jt2.add(b2);
    pane.add(jt2, BorderLayout.SOUTH);
    JButton jb = new JButton("Toggle Action");
    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        action.setEnabled(!action.isEnabled());
      }
    });
    pane.add(jb, BorderLayout.CENTER);
    f.setSize(200, 200);
    f.show();
  }

}

class MyAction extends AbstractAction {
  public MyAction(String name, Icon icon) {
    super(name, icon);
  }

  public void actionPerformed(ActionEvent e) {
    System.out.println("Selected: " + getValue(Action.NAME));
  }
}

class RedOvalIcon implements Icon {
  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(Color.RED);
    if (c.isEnabled()) {
      g.fillOval(x, y, getIconWidth(), getIconHeight());
    } else {
      g.drawOval(x, y, getIconWidth(), getIconHeight());
    }
  }

  public int getIconWidth() {
    return 20;
  }

  public int getIconHeight() {
    return 30;
  }
}