import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JToolBar; public class ActionSample extends JFrame { private Action sampleAction; private Action exitAction; public ActionSample(){ super("Using Actions"); sampleAction = new AbstractAction(){ public void actionPerformed(ActionEvent event){ JOptionPane.showMessageDialog(ActionSample.this, "The sampleAction was invoked!"); exitAction.setEnabled(true); } }; sampleAction.putValue(Action.NAME, "Sample Action"); sampleAction.putValue(Action.SHORT_DESCRIPTION, "A Sample Action"); sampleAction.putValue(Action.MNEMONIC_KEY, new Integer('s')); exitAction = new AbstractAction(){ public void actionPerformed(ActionEvent event){ JOptionPane.showMessageDialog(ActionSample.this, "The exitAction was invoked"); System.exit(0); } }; exitAction.putValue(Action.NAME, "Exit"); exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit Application"); exitAction.putValue(Action.MNEMONIC_KEY, new Integer('x')); exitAction.setEnabled(false); JMenu fileMenu = new JMenu("File"); fileMenu.add(sampleAction); fileMenu.add(exitAction); fileMenu.setMnemonic('F'); JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); setJMenuBar(menuBar); JToolBar toolBar = new JToolBar(); toolBar.add(sampleAction); toolBar.add(exitAction); JButton sampleButton = new JButton(); sampleButton.setAction(sampleAction); JButton exitButton = new JButton(exitAction); JPanel buttonPanel = new JPanel(); buttonPanel.add(sampleButton); buttonPanel.add(exitButton); Container container = getContentPane(); container.add(toolBar, BorderLayout.NORTH); container.add(buttonPanel, BorderLayout.CENTER); } public static void main(String args[]){ ActionSample sample = new ActionSample(); sample.setDefaultCloseOperation(EXIT_ON_CLOSE); sample.pack(); sample.setVisible(true); } }
C++, Java, Python, PHP, Programming Tips, Linux, Bash Shell Scripting, Security And Tech Stuff
Sunday, March 27, 2011
Design pattern with Swing Actions
Labels:
abstractaction,
action,
swing
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment