import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class ActionExample extends JPanel
{
private static final long serialVersionUID = 1L;
private Action actions[] = { new ActionA(), new ActionB(), new ActionC() };
public ActionExample()
{
super();
initUI();
}
private void initUI()
{
setLayout(new FlowLayout());
for (Action action : actions)
{
add(new JButton(action));
}
}
class ActionA extends AbstractAction
{
private static final long serialVersionUID = 1L;
public ActionA()
{
super("A");
putValue(SHORT_DESCRIPTION, "Aktion A");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, 0));
// siehe auch andere Properties, wie ICON etc.
}
public void actionPerformed(ActionEvent e)
{
System.out.println(String.format("%s ausgeführt.", getValue(SHORT_DESCRIPTION)));
}
}
class ActionB extends AbstractAction
{
private static final long serialVersionUID = 1L;
public ActionB()
{
super("B");
putValue(SHORT_DESCRIPTION, "Aktion B");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_B, 0));
// siehe auch andere Properties, wie ICON etc.
}
public void actionPerformed(ActionEvent e)
{
System.out.println(String.format("%s ausgeführt.", getValue(SHORT_DESCRIPTION)));
}
}
class ActionC extends AbstractAction
{
private static final long serialVersionUID = 1L;
public ActionC()
{
super("C");
putValue(SHORT_DESCRIPTION, "Aktion C");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C, 0));
// siehe auch andere Properties, wie ICON etc.
}
public void actionPerformed(ActionEvent e)
{
System.out.println(String.format("%s ausgeführt.", getValue(SHORT_DESCRIPTION)));
}
}
public static void main(String[] args)
{
final JFrame frame = new JFrame("Action Example");
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent p_e)
{
frame.setVisible(false);
System.exit(0);
}
});
frame.setContentPane(new ActionExample());
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}