Java/Swing JFC/Various Event Listener
Содержание
- 1 Demonstrating the ActionListener
- 2 Demonstrating the AdjustmentListener
- 3 Demonstrating the AncestorListener
- 4 Demonstrating the ComponentListener
- 5 Demonstrating the ContainerListener
- 6 Demonstrating the FocusListener
- 7 Demonstrating the HyperlinkListener
- 8 Demonstrating the InternalFrameListener
- 9 Demonstrating the ItemListener
- 10 Demonstrating the KeyListener
- 11 Demonstrating the MenuListener
- 12 Demonstrating the MouseListener and MouseMotionListener
- 13 Demonstrating the MouseWheelListener
- 14 Demonstrating the PopupMenuListener
- 15 Demonstrating the WindowListener
- 16 Demonstrating the WindowListener with a WindowAdapter
- 17 Responding to Keystrokes
Demonstrating the ActionListener
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ActionTest {
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Command: " + e.getActionCommand());
System.out.println("Modifiers: ");
int modifiers = e.getModifiers();
System.out.println("\tALT : "
+ checkMod(modifiers, ActionEvent.ALT_MASK));
System.out.println("\tCTRL : "
+ checkMod(modifiers, ActionEvent.CTRL_MASK));
System.out.println("\tMETA : "
+ checkMod(modifiers, ActionEvent.META_MASK));
System.out.println("\tSHIFT: "
+ checkMod(modifiers, ActionEvent.SHIFT_MASK));
Object source = e.getSource();
if (source instanceof JComboBox) {
JComboBox jb = (JComboBox) source;
System.out.println("Combo: " + jb.getSelectedItem());
}
}
private boolean checkMod(int modifiers, int mask) {
return ((modifiers & mask) == mask);
}
};
String flavors[] = { "Item 1", "Item 2", "Item 3"};
JComboBox jc = new JComboBox(flavors);
jc.setMaximumRowCount(4);
jc.setEditable(true);
jc.addActionListener(listener);
contentPane.add(jc, BorderLayout.NORTH);
JButton b = new JButton("Button!");
b.addActionListener(listener);
contentPane.add(b, BorderLayout.CENTER);
JPanel panel = new JPanel();
JLabel label = new JLabel("Label 1: ");
JTextField text = new JTextField("Type your text", 15);
text.addActionListener(listener);
label.setDisplayedMnemonic(KeyEvent.VK_1);
label.setLabelFor(text);
panel.add(label);
panel.add(text);
contentPane.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.show();
}
}
Demonstrating the AdjustmentListener
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
public class AdjustmentTest {
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
Icon icon = new ImageIcon("jexp.gif");
JButton b = new JButton(icon);
JScrollPane pane = new JScrollPane(b);
AdjustmentListener hListener = new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("Horizontal: ");
dumpInfo(e);
}
};
JScrollBar hBar = pane.getHorizontalScrollBar();
hBar.addAdjustmentListener(hListener);
AdjustmentListener vListener = new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("Vertical: ");
dumpInfo(e);
}
};
JScrollBar vBar = pane.getVerticalScrollBar();
vBar.addAdjustmentListener(vListener);
contentPane.add(pane, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.show();
}
private static void dumpInfo(AdjustmentEvent e) {
System.out.println("\tValue: " + e.getValue());
String type = null;
switch (e.getAdjustmentType()) {
case AdjustmentEvent.TRACK:
type = "Track";
break;
case AdjustmentEvent.BLOCK_DECREMENT:
type = "Block Decrement";
break;
case AdjustmentEvent.BLOCK_INCREMENT:
type = "Block Increment";
break;
case AdjustmentEvent.UNIT_DECREMENT:
type = "Unit Decrement";
break;
case AdjustmentEvent.UNIT_INCREMENT:
type = "Unit Increment";
break;
}
System.out.println("\tType: " + type);
}
}
Demonstrating the AncestorListener
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
public class AncestorTest {
public static void main(String args[]) {
final JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
JButton b = new JButton("Hide for 5");
ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
frame.setVisible(false);
TimerTask task = new TimerTask() {
public void run() {
frame.setVisible(true);
}
};
Timer timer = new Timer();
timer.schedule(task, 5000);
}
};
b.addActionListener(action);
AncestorListener ancestor = new AncestorListener() {
public void ancestorAdded(AncestorEvent e) {
System.out.println("Added");
dumpInfo(e);
}
public void ancestorMoved(AncestorEvent e) {
System.out.println("Moved");
dumpInfo(e);
}
public void ancestorRemoved(AncestorEvent e) {
System.out.println("Removed");
dumpInfo(e);
}
private void dumpInfo(AncestorEvent e) {
System.out.println("\tAncestor: " + name(e.getAncestor()));
System.out.println("\tAncestorParent: "
+ name(e.getAncestorParent()));
System.out.println("\tComponent: " + name(e.getComponent()));
}
private String name(Container c) {
return (c == null) ? null : c.getName();
}
};
b.addAncestorListener(ancestor);
contentPane.add(b, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.show();
}
}
Demonstrating the ComponentListener
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ruponentEvent;
import java.awt.event.ruponentListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
public class SwingComponentTest {
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
ComponentListener comp = new ComponentListener() {
public void componentHidden(ComponentEvent e) {
dump("Hidden", e);
}
public void componentMoved(ComponentEvent e) {
dump("Moved", e);
}
public void componentResized(ComponentEvent e) {
dump("Resized", e);
}
public void componentShown(ComponentEvent e) {
dump("Shown", e);
}
private void dump(String type, ComponentEvent e) {
System.out.println(e.getComponent().getName() + " : " + type);
}
};
JButton left = new JButton("Left");
left.setName("Left");
left.addComponentListener(comp);
final JButton right = new JButton("Right");
right.setName("Right");
right.addComponentListener(comp);
ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent e) {
right.setVisible(!right.isVisible());
}
};
left.addActionListener(action);
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
left, right);
contentPane.add(pane, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.show();
}
}
Demonstrating the ContainerListener
import java.awt.ruponent;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ContainerTest {
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
ContainerListener cont = new ContainerListener() {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Selected: " + e.getActionCommand());
}
};
public void componentAdded(ContainerEvent e) {
Component c = e.getChild();
if (c instanceof JButton) {
JButton b = (JButton) c;
b.addActionListener(listener);
}
}
public void componentRemoved(ContainerEvent e) {
Component c = e.getChild();
if (c instanceof JButton) {
JButton b = (JButton) c;
b.removeActionListener(listener);
}
}
};
contentPane.addContainerListener(cont);
contentPane.setLayout(new GridLayout(3, 2));
contentPane.add(new JButton("First"));
contentPane.add(new JButton("Second"));
contentPane.add(new JButton("Third"));
contentPane.add(new JButton("Fourth"));
contentPane.add(new JButton("Fifth"));
frame.setSize(300, 200);
frame.show();
}
}
Demonstrating the FocusListener
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FocusTest {
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
FocusListener listener = new FocusListener() {
public void focusGained(FocusEvent e) {
dumpInfo(e);
}
public void focusLost(FocusEvent e) {
dumpInfo(e);
}
private void dumpInfo(FocusEvent e) {
System.out.println("Source : " + name(e.getComponent()));
System.out.println("Opposite : "
+ name(e.getOppositeComponent()));
System.out.println("Temporary: " + e.isTemporary());
}
private String name(Component c) {
return (c == null) ? null : c.getName();
}
};
// First
JPanel panel = new JPanel();
JLabel label = new JLabel("Label 1: ");
JTextField text = new JTextField("Type your text", 15);
text.setName("First");
text.addFocusListener(listener);
label.setDisplayedMnemonic(KeyEvent.VK_1);
label.setLabelFor(text);
panel.add(label);
panel.add(text);
contentPane.add(panel, BorderLayout.NORTH);
// Second
panel = new JPanel();
label = new JLabel("Label 2: ");
text = new JTextField("14.0", 10);
text.setName("Second");
text.addFocusListener(listener);
text.setHorizontalAlignment(JTextField.RIGHT);
label.setDisplayedMnemonic(KeyEvent.VK_2);
label.setLabelFor(text);
panel.add(label);
panel.add(text);
contentPane.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.show();
}
}
Demonstrating the HyperlinkListener
import java.awt.BorderLayout;
import java.awt.Container;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class HyperlinkTest {
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
final JEditorPane ep = new JEditorPane();
try {
ep.setPage("http://www.jexp.ru");
} catch (IOException e) {
System.err.println("Bad URL: " + e);
System.exit(-1);
}
HyperlinkListener listener = new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
ep.setPage(e.getURL());
} catch (IOException ioe) {
System.err.println("Error loading: " + ioe);
}
}
}
};
ep.addHyperlinkListener(listener);
ep.setEditable(false);
JScrollPane pane = new JScrollPane(ep);
contentPane.add(pane, BorderLayout.CENTER);
frame.setSize(640, 480);
frame.show();
}
}
Demonstrating the InternalFrameListener
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
public class InternalFrameTest {
public static void main(String args[]) {
JFrame frame = new JFrame("Internal Frame Listener");
Container contentPane = frame.getContentPane();
JLayeredPane desktop = new JDesktopPane();
desktop.setOpaque(false);
desktop.add(createLayer("One"), JLayeredPane.POPUP_LAYER);
desktop.add(createLayer("Two"), JLayeredPane.DEFAULT_LAYER);
desktop.add(createLayer("Three"), JLayeredPane.PALETTE_LAYER);
contentPane.add(desktop, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.show();
}
static JInternalFrame createLayer(String label) {
return new SelfInternalFrame(label);
}
static class SelfInternalFrame extends JInternalFrame {
InternalFrameListener listener = new InternalFrameListener() {
public void internalFrameActivated(InternalFrameEvent e) {
dumpInfo("Activated", e);
}
public void internalFrameClosed(InternalFrameEvent e) {
dumpInfo("Closed", e);
}
public void internalFrameClosing(InternalFrameEvent e) {
dumpInfo("Closing", e);
}
public void internalFrameDeactivated(InternalFrameEvent e) {
dumpInfo("Deactivated", e);
}
public void internalFrameDeiconified(InternalFrameEvent e) {
dumpInfo("Deiconified", e);
}
public void internalFrameIconified(InternalFrameEvent e) {
dumpInfo("Iconified", e);
}
public void internalFrameOpened(InternalFrameEvent e) {
dumpInfo("Opened", e);
}
private void dumpInfo(String s, InternalFrameEvent e) {
System.out.println("Source: " + e.getInternalFrame().getName()
+ " : " + s);
}
};
public SelfInternalFrame(String s) {
getContentPane().add(new JLabel(s, JLabel.CENTER),
BorderLayout.CENTER);
setName(s);
addInternalFrameListener(listener);
setBounds(50, 50, 100, 100);
setResizable(true);
setClosable(true);
setMaximizable(true);
setIconifiable(true);
setTitle(s);
setVisible(true);
}
}
}
Demonstrating the ItemListener
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class ItemTest {
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println("Source: " + name(e.getSource()));
System.out.println("Item: " + name(e.getItem()));
int state = e.getStateChange();
System.out.println("State: "
+ ((state == ItemEvent.SELECTED) ? "Selected"
: "Deselected"));
}
private String name(Object o) {
if (o instanceof JComponent) {
JComponent comp = (JComponent) o;
return comp.getName();
} else {
return o.toString();
}
}
};
JPanel panel = new JPanel(new GridLayout(0, 1));
ButtonGroup group = new ButtonGroup();
JRadioButton option = new JRadioButton("French Fries", true);
option.setName(option.getText());
option.addItemListener(listener);
group.add(option);
panel.add(option);
option = new JRadioButton("Onion Rings", false);
option.setName(option.getText());
option.addItemListener(listener);
group.add(option);
panel.add(option);
option = new JRadioButton("Ice Cream", false);
option.setName(option.getText());
option.addItemListener(listener);
group.add(option);
panel.add(option);
contentPane.add(panel, BorderLayout.NORTH);
String flavors[] = { "Item 1", "Item 2", "Item 3"};
JComboBox jc = new JComboBox(flavors);
jc.setName("Combo");
jc.addItemListener(listener);
jc.setMaximumRowCount(4);
contentPane.add(jc, BorderLayout.SOUTH);
frame.pack();
frame.show();
}
}
Demonstrating the KeyListener
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class KeyTest {
public static void main(String args[]) {
JFrame frame = new JFrame("Key Listener");
Container contentPane = frame.getContentPane();
KeyListener listener = new KeyListener() {
public void keyPressed(KeyEvent e) {
dumpInfo("Pressed", e);
}
public void keyReleased(KeyEvent e) {
dumpInfo("Released", e);
}
public void keyTyped(KeyEvent e) {
dumpInfo("Typed", e);
}
private void dumpInfo(String s, KeyEvent e) {
System.out.println(s);
int code = e.getKeyCode();
System.out.println("\tCode: " + KeyEvent.getKeyText(code));
System.out.println("\tChar: " + e.getKeyChar());
int mods = e.getModifiersEx();
System.out.println("\tMods: "
+ KeyEvent.getModifiersExText(mods));
System.out.println("\tLocation: "
+ location(e.getKeyLocation()));
System.out.println("\tAction? " + e.isActionKey());
}
private String location(int location) {
switch (location) {
case KeyEvent.KEY_LOCATION_LEFT:
return "Left";
case KeyEvent.KEY_LOCATION_RIGHT:
return "Right";
case KeyEvent.KEY_LOCATION_NUMPAD:
return "NumPad";
case KeyEvent.KEY_LOCATION_STANDARD:
return "Standard";
case KeyEvent.KEY_LOCATION_UNKNOWN:
default:
return "Unknown";
}
}
};
JTextField text = new JTextField();
text.addKeyListener(listener);
contentPane.add(text, BorderLayout.NORTH);
frame.pack();
frame.show();
}
}
Demonstrating the MenuListener
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
public class MenuTest extends JFrame {
public MenuTest() {
super();
MenuListener listener = new MenuListener() {
public void menuCanceled(MenuEvent e) {
dumpInfo("Canceled", e);
}
public void menuDeselected(MenuEvent e) {
dumpInfo("Deselected", e);
}
public void menuSelected(MenuEvent e) {
dumpInfo("Selected", e);
}
private void dumpInfo(String s, MenuEvent e) {
JMenu menu = (JMenu) e.getSource();
System.out.println(s + ": " + menu.getText());
}
};
JMenu fileMenu = new JMenu("File");
fileMenu.addMenuListener(listener);
fileMenu.add(new JMenuItem("Open"));
fileMenu.add(new JMenuItem("Close"));
fileMenu.add(new JMenuItem("Exit"));
JMenu helpMenu = new JMenu("Help");
helpMenu.addMenuListener(listener);
helpMenu.add(new JMenuItem("About MenuTest"));
helpMenu.add(new JMenuItem("Class Hierarchy"));
helpMenu.addSeparator();
helpMenu.add(new JCheckBoxMenuItem("Balloon Help"));
JMenu subMenu = new JMenu("Categories");
subMenu.addMenuListener(listener);
JRadioButtonMenuItem rb;
ButtonGroup group = new ButtonGroup();
subMenu.add(rb = new JRadioButtonMenuItem("A Little Help", true));
group.add(rb);
subMenu.add(rb = new JRadioButtonMenuItem("A Lot of Help"));
group.add(rb);
helpMenu.add(subMenu);
JMenuBar mb = new JMenuBar();
mb.add(fileMenu);
mb.add(helpMenu);
setJMenuBar(mb);
}
public static void main(String args[]) {
JFrame frame = new MenuTest();
frame.setSize(300, 300);
frame.show();
}
}
Demonstrating the MouseListener and MouseMotionListener
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class MouseTest extends JFrame {
int startX, startY, endX, endY;
Color color = Color.BLACK;
public MouseTest() {
super();
final JPopupMenu pop = new JPopupMenu();
pop.add(new JMenuItem("Cut"));
pop.add(new JMenuItem("Copy"));
pop.add(new JMenuItem("Paste"));
pop.addSeparator();
pop.add(new JMenuItem("Select All"));
pop.setInvoker(this);
MouseListener popup = new MouseListener() {
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopup(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopup(e);
}
}
private void showPopup(MouseEvent e) {
pop.show(e.getComponent(), e.getX(), e.getY());
}
};
addMouseListener(popup);
MouseListener drawing1 = new MouseListener() {
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
color = Color.RED;
startX = endX = e.getX();
startY = endY = e.getY();
repaint();
}
public void mouseReleased(MouseEvent e) {
color = Color.BLACK;
repaint();
}
};
addMouseListener(drawing1);
MouseMotionListener drawing2 = new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
endX = e.getX();
endY = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e) {
}
};
addMouseMotionListener(drawing2);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(color);
g.drawLine(startX, startY, endX, endY);
}
public static void main(String args[]) {
JFrame frame = new MouseTest();
frame.setSize(300, 300);
frame.show();
}
}
Demonstrating the MouseWheelListener
import java.awt.Color;
import java.awt.Container;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JFrame;
public class MouseWheelTest extends JFrame {
private static final Color colors[] = { Color.BLACK, Color.BLUE,
Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN,
Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK,
Color.RED, Color.WHITE, Color.YELLOW };
public MouseWheelTest() {
super();
final Container contentPane = getContentPane();
MouseWheelListener listener = new MouseWheelListener() {
int colorCounter;
private static final int UP = 1;
private static final int DOWN = 2;
public void mouseWheelMoved(MouseWheelEvent e) {
int count = e.getWheelRotation();
int direction = (Math.abs(count) > 0) ? UP : DOWN;
changeBackground(direction);
}
private void changeBackground(int direction) {
contentPane.setBackground(colors[colorCounter]);
if (direction == UP) {
colorCounter++;
} else {
--colorCounter;
}
if (colorCounter == colors.length) {
colorCounter = 0;
} else if (colorCounter < 0) {
colorCounter = colors.length - 1;
}
}
};
contentPane.addMouseWheelListener(listener);
}
public static void main(String args[]) {
JFrame frame = new MouseWheelTest();
frame.setSize(300, 300);
frame.show();
}
}
Demonstrating the PopupMenuListener
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.ruboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class PopupTest {
public static void main(String args[]) {
JFrame frame = new JFrame("Popup Menu Listener");
Container contentPane = frame.getContentPane();
final String flavors[] = { "Item 1", "Item 2", "Item 3"};
PopupMenuListener listener = new PopupMenuListener() {
boolean initialized = false;
public void popupMenuCanceled(PopupMenuEvent e) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
if (!initialized) {
JComboBox combo = (JComboBox) e.getSource();
ComboBoxModel model = new DefaultComboBoxModel(flavors);
combo.setModel(model);
initialized = true;
}
}
};
JComboBox jc = new JComboBox();
jc.addPopupMenuListener(listener);
jc.setMaximumRowCount(4);
jc.setEditable(true);
contentPane.add(jc, BorderLayout.NORTH);
frame.pack();
frame.show();
}
}
Demonstrating the WindowListener
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class WindowTest {
public static void main(String args[]) {
JFrame frame = new JFrame("Window Listener");
WindowListener listener = new WindowListener() {
public void windowActivated(WindowEvent w) {
System.out.println(w);
}
public void windowClosed(WindowEvent w) {
System.out.println(w);
}
public void windowClosing(WindowEvent w) {
System.out.println(w);
System.exit(0);
}
public void windowDeactivated(WindowEvent w) {
System.out.println(w);
}
public void windowDeiconified(WindowEvent w) {
System.out.println(w);
}
public void windowIconified(WindowEvent w) {
System.out.println(w);
}
public void windowOpened(WindowEvent w) {
System.out.println(w);
}
};
frame.addWindowListener(listener);
frame.setSize(300, 300);
frame.show();
}
}
Demonstrating the WindowListener with a WindowAdapter
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class WindowAdapterTest {
public static void main(String args[]) {
JFrame frame = new JFrame("Window Listener");
WindowListener listener = new WindowAdapter() {
public void windowClosing(WindowEvent w) {
System.exit(0);
}
};
frame.addWindowListener(listener);
frame.setSize(300, 300);
frame.show();
}
}
Responding to Keystrokes
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
public class KeyTester {
static class MyActionListener extends AbstractAction {
MyActionListener(String s) {
super(s);
}
public void actionPerformed(ActionEvent e) {
System.out.println(getValue(Action.NAME));
}
}
public static void main(String args[]) {
String actionKey = "theAction";
JFrame f = new JFrame("Key Tester");
JButton jb1 = new JButton("<html><center>B<br>Focused/Typed");
JButton jb2 = new JButton("<html><center>Ctrl-C<br>Window/Pressed");
JButton jb3 = new JButton("<html><center>Shift-D<br>Ancestor/Released");
Container pane = f.getContentPane();
pane.add(jb1, BorderLayout.NORTH);
pane.add(jb2, BorderLayout.CENTER);
pane.add(jb3, BorderLayout.SOUTH);
KeyStroke stroke = KeyStroke.getKeyStroke("typed B");
Action action = new MyActionListener("Action Happened");
// Defaults to JComponent.WHEN_FOCUSED map
InputMap inputMap = jb1.getInputMap();
inputMap.put(stroke, actionKey);
ActionMap actionMap = jb1.getActionMap();
actionMap.put(actionKey, action);
stroke = KeyStroke.getKeyStroke("ctrl C");
action = new MyActionListener("Action Didn"t Happen");
inputMap = jb2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(stroke, actionKey);
actionMap = jb2.getActionMap();
actionMap.put(actionKey, action);
stroke = KeyStroke.getKeyStroke("shift released D");
action = new MyActionListener("What Happened?");
inputMap = jb3
.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(stroke, actionKey);
actionMap = jb3.getActionMap();
actionMap.put(actionKey, action);
f.setSize(200, 200);
f.show();
}
}