Java/Event/Various Event Listener
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 A ComponentAdapter.
- 2 Action, Mouse Focus
- 3 A demonstration of the ChangeEvents generated by the BoundedRangeModel
- 4 An application that shows the Action class in, well, action
- 5 AncestorListener Demo
- 6 A position of a window on the screen.
- 7 CheckBox Item Listener
- 8 Component Event Demo
- 9 Container Event Demo
- 10 Demonstrating the ActionListener
- 11 Demonstrating the AdjustmentListener
- 12 Demonstrating the AncestorListener
- 13 Demonstrating the ComponentListener
- 14 Demonstrating the ContainerListener
- 15 Demonstrating the FocusListener
- 16 Demonstrating the HyperlinkListener
- 17 Demonstrating the InternalFrameListener
- 18 Demonstrating the ItemListener
- 19 Demonstrating the KeyListener
- 20 Demonstrating the MenuListener
- 21 Demonstrating the MouseListener and MouseMotionListener
- 22 Demonstrating the MouseWheelListener
- 23 Demonstrating the PopupMenuListener
- 24 Demonstrating the WindowListener
- 25 Demonstrating the WindowListener with a WindowAdapter
- 26 Display the addXXXListener methods of any Swing class
- 27 EventListenerList enabled Secret Label
- 28 Focus Event Demo
- 29 Focus Next Component Sample
- 30 Handle a window closing event
- 31 Implement a graphical list selection monitor
- 32 implements VetoableChangeListener to block focus change events
- 33 Installs/resets a ComponentListener to resize the given window to minWidth/Height if needed
- 34 ItemListener for JRadioButton
- 35 JAR Archives: Pack Progress Monitor
- 36 KeyListener, ActionListener Demo 1
- 37 KeyListener, ActionListener Demo 2
- 38 KeyStroke Sample
- 39 Load Save Action
- 40 PropertyChangeListener Sample
- 41 Responding to Keystrokes
- 42 Show events as they happen
- 43 Showing how to add Actions for KeyStrokes
- 44 Sketch
- 45 StateChange Listener
- 46 Swing Action Demo
- 47 TextAction example
- 48 Timer Sample
- 49 Using ComponentListener to catch the JFrame Maximization event
- 50 Window Event Demo
A ComponentAdapter.
import java.awt.event.ruponentAdapter;
import java.awt.event.ruponentEvent;
import javax.swing.JFrame;
class MoveAdapter extends ComponentAdapter {
public void componentMoved(ComponentEvent e) {
int x = e.getComponent().getX();
int y = e.getComponent().getY();
System.out.println("x: " + x);
System.out.println("y: " + y);
}
}
public class Adapter {
public static void main(String[] args) {
JFrame f = new JFrame();
f.addComponentListener(new MoveAdapter());
f.setSize(310, 200);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
Action, Mouse Focus
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.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FocusSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Focus Sample");
ActionListener actionListener = new ActionFocusMover();
MouseListener mouseListener = new MouseEnterFocusMover();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(3, 3));
for (int i = 1; i < 10; i++) {
JButton button = new JButton("" + i);
button.addActionListener(actionListener);
button.addMouseListener(mouseListener);
if ((i % 2) != 0) {
button.setRequestFocusEnabled(false);
}
contentPane.add(button);
}
frame.setSize(300, 200);
frame.setVisible(true);
}
}
class ActionFocusMover implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
Object source = actionEvent.getSource();
if (source instanceof Component) {
Component component = (Component) source;
component.transferFocus();
}
}
}
class MouseEnterFocusMover extends MouseAdapter {
public void mouseEntered(MouseEvent mouseEvent) {
Component component = mouseEvent.getComponent();
if (!component.hasFocus()) {
component.requestFocus();
}
}
}
A demonstration of the ChangeEvents generated by the BoundedRangeModel
// A demonstration of the ChangeEvents generated by the BoundedRangeModel.
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Bounded {
public Bounded() {
try {
DefaultBoundedRangeModel model = new DefaultBoundedRangeModel();
ChangeListener myListener = new MyChangeListener();
model.addChangeListener(myListener);
System.out.println(model.toString());
System.out.println("Now setting minimum to 50 . . .");
model.setMinimum(50);
System.out.println(model.toString());
System.out.println("Now setting maximum to 40 . . .");
model.setMaximum(40);
System.out.println(model.toString());
System.out.println("Now setting maximum to 50 . . .");
model.setMaximum(50);
System.out.println(model.toString());
System.out.println("Now setting extent to 30 . . .");
model.setExtent(30);
System.out.println(model.toString());
System.out.println("Now setting several properties . . .");
if (!model.getValueIsAdjusting()) {
model.setValueIsAdjusting(true);
System.out.println(model.toString());
model.setMinimum(0);
model.setMaximum(100);
model.setExtent(20);
model.setValueIsAdjusting(false);
}
System.out.println(model.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
class MyChangeListener implements ChangeListener {
public void stateChanged(ChangeEvent e) {
System.out.println("A ChangeEvent has been fired!");
}
}
public static void main(String args[]) {
new Bounded();
}
}
An application that shows the Action class in, well, action
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// ActionExampleSwing.java
//An application that shows the Action class in, well, action.
//
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class ActionExampleSwing extends JFrame {
public static final int MIN_CHANNEL = 2;
public static final int MAX_CHANNEL = 13;
private int currentChannel = MIN_CHANNEL;
private int favoriteChannel = 9;
private JLabel channelLabel = new JLabel();
private Action upAction = new UpAction();
private Action downAction = new DownAction();
private GotoFavoriteAction gotoFavoriteAction = new GotoFavoriteAction();
private Action setFavoriteAction = new SetFavoriteAction();
public class UpAction extends AbstractAction {
public UpAction() {
putValue(NAME, "Channel Up");
putValue(SMALL_ICON, new ImageIcon("images/up.gif"));
putValue(SHORT_DESCRIPTION, "Increment the channel number");
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_U));
}
public void actionPerformed(ActionEvent ae) {
setChannel(currentChannel + 1);
}
}
public class DownAction extends AbstractAction {
public DownAction() {
putValue(NAME, "Channel Down");
putValue(SMALL_ICON, new ImageIcon("images/down.gif"));
putValue(SHORT_DESCRIPTION, "Decrement the channel number");
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_D));
}
public void actionPerformed(ActionEvent ae) {
setChannel(currentChannel - 1);
}
}
public class GotoFavoriteAction extends AbstractAction {
public GotoFavoriteAction() {
putValue(SMALL_ICON, new ImageIcon("images/fav.gif"));
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_G));
updateProperties();
}
public void updateProperties() {
putValue(NAME, "Go to channel " + favoriteChannel);
putValue(SHORT_DESCRIPTION, "Change the channel to "
+ favoriteChannel);
}
public void actionPerformed(ActionEvent ae) {
setChannel(favoriteChannel);
}
}
public class SetFavoriteAction extends AbstractAction {
public SetFavoriteAction() {
putValue(NAME, "Set "Go to" channel");
putValue(SMALL_ICON, new ImageIcon("images/set.gif"));
putValue(SHORT_DESCRIPTION,
"Make current channel the Favorite channel");
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_S));
}
public void actionPerformed(ActionEvent ae) {
favoriteChannel = currentChannel;
gotoFavoriteAction.updateProperties();
setEnabled(false);
gotoFavoriteAction.setEnabled(false);
}
}
public ActionExampleSwing() {
super("ActionExample Swing");
setChannel(currentChannel); // enable/disable the Actions as appropriate
channelLabel.setHorizontalAlignment(JLabel.CENTER);
channelLabel.setFont(new Font("Serif", Font.PLAIN, 32));
getContentPane().add(channelLabel, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(2, 2, 16, 6));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(6, 16, 16, 16));
getContentPane().add(buttonPanel, BorderLayout.CENTER);
buttonPanel.add(new JButton(upAction));
buttonPanel.add(new JButton(gotoFavoriteAction));
buttonPanel.add(new JButton(downAction));
buttonPanel.add(new JButton(setFavoriteAction));
JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("Channel");
menu.add(new JMenuItem(upAction));
menu.add(new JMenuItem(downAction));
menu.addSeparator();
menu.add(new JMenuItem(gotoFavoriteAction));
menu.add(new JMenuItem(setFavoriteAction));
mb.add(menu);
setJMenuBar(mb);
}
public void setChannel(int chan) {
currentChannel = chan;
channelLabel.setText("Now tuned to channel: " + currentChannel);
// enable/disable the Actions as appropriate
downAction.setEnabled(currentChannel > MIN_CHANNEL);
upAction.setEnabled(currentChannel < MAX_CHANNEL);
gotoFavoriteAction.setEnabled(currentChannel != favoriteChannel);
setFavoriteAction.setEnabled(currentChannel != favoriteChannel);
}
public static void main(String argv[]) {
JFrame f = new ActionExampleSwing();
f.setSize(400, 180);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
AncestorListener Demo
import javax.swing.JFrame;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
public class AncestorSampler {
public static void main (String args[]) {
JFrame f = new JFrame("Ancestor Sampler");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AncestorListener ancestorListener = new AncestorListener() {
public void ancestorAdded(AncestorEvent ancestorEvent) {
System.out.println ("Added");
}
public void ancestorMoved(AncestorEvent ancestorEvent) {
System.out.println ("Moved");
}
public void ancestorRemoved(AncestorEvent ancestorEvent) {
System.out.println ("Removed");
}
};
f.getRootPane().addAncestorListener(ancestorListener);
f.getRootPane().setVisible(false);
f.getRootPane().setVisible(true);
f.setSize (300, 200);
f.setVisible (true);
}
}
A position of a window on the screen.
import java.awt.event.ruponentEvent;
import java.awt.event.ruponentListener;
import javax.swing.JFrame;
public class MovingWindow extends JFrame implements ComponentListener {
public MovingWindow() {
addComponentListener(this);
setSize(310, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void componentResized(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
int x = e.getComponent().getX();
int y = e.getComponent().getY();
System.out.println("x: " + x);
System.out.println("y: " + y);
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
public static void main(String[] args) {
new MovingWindow();
}
}
CheckBox Item Listener
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SelectingCheckBox {
private static String DESELECTED_LABEL = "Deselected";
private static String SELECTED_LABEL = "Selected";
public static void main(String args[]) {
JFrame frame = new JFrame("Selecting CheckBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox checkBox = new JCheckBox(DESELECTED_LABEL);
// Define ActionListener
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton)actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
String newLabel = (selected ? SELECTED_LABEL : DESELECTED_LABEL);
abstractButton.setText(newLabel);
}
};
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
AbstractButton abstractButton = (AbstractButton)changeEvent.getSource();
ButtonModel buttonModel = abstractButton.getModel();
boolean armed = buttonModel.isArmed();
boolean pressed = buttonModel.isPressed();
boolean selected = buttonModel.isSelected();
System.out.println("Changed: " + armed + "/" + pressed + "/" + selected);
}
};
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
AbstractButton abstractButton = (AbstractButton)itemEvent.getSource();
Color foreground = abstractButton.getForeground();
Color background = abstractButton.getBackground();
int state = itemEvent.getStateChange();
if (state == ItemEvent.SELECTED) {
abstractButton.setForeground(background);
abstractButton.setBackground(foreground);
}
}
};
checkBox.addActionListener(actionListener);
checkBox.addChangeListener(changeListener);
checkBox.addItemListener(itemListener);
checkBox.setMnemonic(KeyEvent.VK_S);
Container contentPane = frame.getContentPane();
contentPane.add(checkBox, BorderLayout.NORTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
Component Event Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* ComponentEventDemo.java is a 1.4 example that requires no other files.
*/
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.event.ruponentEvent;
import java.awt.event.ruponentListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ComponentEventDemo extends JPanel implements ComponentListener,
ItemListener {
static JFrame frame;
JTextArea display;
JLabel label;
String newline = "\n";
public ComponentEventDemo() {
super(new BorderLayout());
display = new JTextArea();
display.setEditable(false);
JScrollPane scrollPane = new JScrollPane(display);
scrollPane.setPreferredSize(new Dimension(350, 200));
JPanel panel = new JPanel(new BorderLayout());
label = new JLabel("This is a label", JLabel.CENTER);
label.addComponentListener(this);
panel.add(label, BorderLayout.CENTER);
JCheckBox checkbox = new JCheckBox("Label visible", true);
checkbox.addItemListener(this);
checkbox.addComponentListener(this);
panel.add(checkbox, BorderLayout.PAGE_END);
panel.addComponentListener(this);
add(scrollPane, BorderLayout.CENTER);
add(panel, BorderLayout.PAGE_END);
frame.addComponentListener(this);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
label.setVisible(true);
//Need to revalidate and repaint, or else the label
//will probably be drawn in the wrong place.
label.revalidate();
label.repaint();
} else {
label.setVisible(false);
}
}
protected void displayMessage(String message) {
//If the text area is not yet realized, and
//we tell it to draw text, it could cause
//a text/AWT tree deadlock. Our solution is
//to ensure that the text area is realized
//before attempting to draw text.
if (display.isShowing()) {
display.append(message + newline);
display.setCaretPosition(display.getDocument().getLength());
}
}
public void componentHidden(ComponentEvent e) {
displayMessage("componentHidden event from "
+ e.getComponent().getClass().getName());
}
public void componentMoved(ComponentEvent e) {
Component c = e.getComponent();
displayMessage("componentMoved event from " + c.getClass().getName()
+ "; new location: " + c.getLocation().x + ", "
+ c.getLocation().y);
}
public void componentResized(ComponentEvent e) {
Component c = e.getComponent();
displayMessage("componentResized event from " + c.getClass().getName()
+ "; new size: " + c.getSize().width + ", "
+ c.getSize().height);
}
public void componentShown(ComponentEvent e) {
displayMessage("componentShown event from "
+ e.getComponent().getClass().getName());
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
frame = new JFrame("ComponentEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ComponentEventDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Container Event Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* ContainerEventDemo.java is a 1.4 example that requires no other files.
*/
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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 java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ContainerEventDemo extends JPanel implements ContainerListener,
ActionListener {
JTextArea display;
JPanel buttonPanel;
JButton addButton, removeButton, clearButton;
Vector buttonList;
static final String ADD = "add";
static final String REMOVE = "remove";
static final String CLEAR = "clear";
static final String newline = "\n";
public ContainerEventDemo() {
super(new GridBagLayout());
GridBagLayout gridbag = (GridBagLayout) getLayout();
GridBagConstraints c = new GridBagConstraints();
//Initialize an empty list of buttons.
buttonList = new Vector(10, 10);
//Create all the components.
addButton = new JButton("Add a button");
addButton.setActionCommand(ADD);
addButton.addActionListener(this);
removeButton = new JButton("Remove a button");
removeButton.setActionCommand(REMOVE);
removeButton.addActionListener(this);
buttonPanel = new JPanel(new GridLayout(1, 1));
buttonPanel.setPreferredSize(new Dimension(200, 75));
buttonPanel.addContainerListener(this);
display = new JTextArea();
display.setEditable(false);
JScrollPane scrollPane = new JScrollPane(display);
scrollPane.setPreferredSize(new Dimension(200, 75));
clearButton = new JButton("Clear text area");
clearButton.setActionCommand(CLEAR);
clearButton.addActionListener(this);
c.fill = GridBagConstraints.BOTH; //Fill entire cell.
c.weighty = 1.0; //Button area and message area have equal height.
c.gridwidth = GridBagConstraints.REMAINDER; //end of row
gridbag.setConstraints(scrollPane, c);
add(scrollPane);
c.weighty = 0.0;
gridbag.setConstraints(clearButton, c);
add(clearButton);
c.weightx = 1.0; //Add/remove buttons have equal width.
c.gridwidth = 1; //NOT end of row
gridbag.setConstraints(addButton, c);
add(addButton);
c.gridwidth = GridBagConstraints.REMAINDER; //end of row
gridbag.setConstraints(removeButton, c);
add(removeButton);
c.weighty = 1.0; //Button area and message area have equal height.
gridbag.setConstraints(buttonPanel, c);
add(buttonPanel);
setPreferredSize(new Dimension(400, 400));
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
public void componentAdded(ContainerEvent e) {
displayMessage(" added to ", e);
}
public void componentRemoved(ContainerEvent e) {
displayMessage(" removed from ", e);
}
void displayMessage(String action, ContainerEvent e) {
display.append(((JButton) e.getChild()).getText() + " was" + action
+ e.getContainer().getClass().getName() + newline);
display.setCaretPosition(display.getDocument().getLength());
}
/*
* This could have been implemented as two or three classes or objects, for
* clarity.
*/
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (ADD.equals(command)) {
JButton newButton = new JButton("JButton #"
+ (buttonList.size() + 1));
buttonList.addElement(newButton);
buttonPanel.add(newButton);
buttonPanel.revalidate(); //Make the button show up.
} else if (REMOVE.equals(command)) {
int lastIndex = buttonList.size() - 1;
try {
JButton nixedButton = (JButton) buttonList.elementAt(lastIndex);
buttonPanel.remove(nixedButton);
buttonList.removeElementAt(lastIndex);
buttonPanel.revalidate(); //Make the button disappear.
buttonPanel.repaint(); //Make the button disappear.
} catch (ArrayIndexOutOfBoundsException exc) {
}
} else if (CLEAR.equals(command)) {
display.setText("");
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("ContainerEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ContainerEventDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
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 ComponentTest {
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();
}
}
Display the addXXXListener methods of any Swing class
// : c14:ShowAddListeners.java
// Display the "addXXXListener" methods of any Swing class.
// <applet code=ShowAddListeners
// width=500 height=400></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ShowAddListeners extends JApplet {
private JTextField name = new JTextField(25);
private JTextArea results = new JTextArea(40, 65);
private static Pattern addListener = Pattern
.rupile("(add\\w+?Listener\\(.*?\\))");
private static Pattern qualifier = Pattern.rupile("\\w+\\.");
class NameL implements ActionListener {
public void actionPerformed(ActionEvent e) {
String nm = name.getText().trim();
if (nm.length() == 0) {
results.setText("No match");
return;
}
Class klass;
try {
klass = Class.forName("javax.swing." + nm);
} catch (ClassNotFoundException ex) {
results.setText("No match");
return;
}
Method[] methods = klass.getMethods();
results.setText("");
for (int i = 0; i < methods.length; i++) {
Matcher matcher = addListener.matcher(methods[i].toString());
if (matcher.find())
results.append(qualifier.matcher(matcher.group(1))
.replaceAll("")
+ "\n");
}
}
}
public void init() {
NameL nameListener = new NameL();
name.addActionListener(nameListener);
JPanel top = new JPanel();
top.add(new JLabel("Swing class name (press ENTER):"));
top.add(name);
Container cp = getContentPane();
cp.add(BorderLayout.NORTH, top);
cp.add(new JScrollPane(results));
// Initial data and test:
name.setText("JTextArea");
nameListener.actionPerformed(new ActionEvent("", 0, ""));
}
public static void main(String[] args) {
run(new ShowAddListeners(), 500, 400);
}
public static void run(JApplet applet, int width, int height) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(width, height);
applet.init();
applet.start();
frame.setVisible(true);
}
} ///:~
EventListenerList enabled Secret Label
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// SecretTest.java
//A demonstration framework for the EventListenerList-enabled SecretLabel class
//
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SecretTest extends JFrame {
public SecretTest() {
super("EventListenerList Demo");
setSize(200, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
SecretLabel secret = new SecretLabel("Try Clicking Me");
final JLabel reporter = new JLabel("Event reports will show here...");
secret.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
reporter.setText("Got it: " + ae.getActionCommand());
}
});
getContentPane().add(secret, BorderLayout.NORTH);
getContentPane().add(reporter, BorderLayout.SOUTH);
}
public static void main(String args[]) {
SecretTest st = new SecretTest();
st.setVisible(true);
}
}
//SecretLabel.java
//An extension of the JLabel class that listens to mouse clicks and converts
//them to ActionEvents, which in turn are reported via an EventListenersList
//object
//
class SecretLabel extends JLabel {
public SecretLabel(String msg) {
super(msg);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
fireActionPerformed(new ActionEvent(SecretLabel.this,
ActionEvent.ACTION_PERFORMED, "SecretMessage"));
}
});
}
public void addActionListener(ActionListener l) {
// We"ll just use the listenerList we inherit from JComponent.
listenerList.add(ActionListener.class, l);
}
public void removeActionListener(ActionListener l) {
listenerList.remove(ActionListener.class, l);
}
protected void fireActionPerformed(ActionEvent ae) {
Object[] listeners = listenerList.getListeners(ActionListener.class);
for (int i = 0; i < listeners.length; i++) {
((ActionListener) listeners[i]).actionPerformed(ae);
}
}
}
Focus Event Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* FocusEventDemo.java is a 1.4 example that requires no other files.
*/
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class FocusEventDemo extends JPanel implements FocusListener {
final static String newline = "\n";
JTextArea display;
public FocusEventDemo() {
super(new GridBagLayout());
GridBagLayout gridbag = (GridBagLayout) getLayout();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0; //Make column as wide as possible.
JTextField textField = new JTextField("A TextField");
textField.setMargin(new Insets(0, 2, 0, 2));
textField.addFocusListener(this);
gridbag.setConstraints(textField, c);
add(textField);
c.weightx = 0.1; //Widen every other column a bit, when possible.
c.fill = GridBagConstraints.NONE;
JLabel label = new JLabel("A Label");
label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
label.addFocusListener(this);
gridbag.setConstraints(label, c);
add(label);
String comboPrefix = "ComboBox Item #";
final int numItems = 15;
Vector vector = new Vector(numItems);
for (int i = 0; i < numItems; i++) {
vector.addElement(comboPrefix + i);
}
JComboBox comboBox = new JComboBox(vector);
comboBox.addFocusListener(this);
gridbag.setConstraints(comboBox, c);
add(comboBox);
c.gridwidth = GridBagConstraints.REMAINDER;
JButton button = new JButton("A Button");
button.addFocusListener(this);
gridbag.setConstraints(button, c);
add(button);
c.weightx = 0.0;
c.weighty = 0.1;
c.fill = GridBagConstraints.BOTH;
String listPrefix = "List Item #";
Vector listVector = new Vector(numItems);
for (int i = 0; i < numItems; i++) {
listVector.addElement(listPrefix + i);
}
JList list = new JList(listVector);
list.setSelectedIndex(1); //It"s easier to see the focus change
//if an item is selected.
list.addFocusListener(this);
JScrollPane listScrollPane = new JScrollPane(list);
//We want to prevent the list"s scroll bars
//from getting the focus - even with the keyboard.
//Note that in general we prefer setRequestFocusable
//over setFocusable for reasons of accessibility,
//but this is to work around bug #4866958.
listScrollPane.getVerticalScrollBar().setFocusable(false);
listScrollPane.getHorizontalScrollBar().setFocusable(false);
gridbag.setConstraints(listScrollPane, c);
add(listScrollPane);
c.weighty = 1.0; //Make this row as tall as possible.
c.gridheight = GridBagConstraints.REMAINDER;
//Set up the area that reports focus-gained and focus-lost events.
display = new JTextArea();
display.setEditable(false);
//The method setRequestFocusEnabled prevents a
//component from being clickable, but it can still
//get the focus through the keyboard - this ensures
//user accessibility.
display.setRequestFocusEnabled(false);
display.addFocusListener(this);
JScrollPane displayScrollPane = new JScrollPane(display);
//Work around for bug #4866958.
displayScrollPane.getHorizontalScrollBar().setFocusable(false);
displayScrollPane.getVerticalScrollBar().setFocusable(false);
gridbag.setConstraints(displayScrollPane, c);
add(displayScrollPane);
setPreferredSize(new Dimension(450, 450));
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
public void focusGained(FocusEvent e) {
displayMessage("Focus gained", e);
}
public void focusLost(FocusEvent e) {
displayMessage("Focus lost", e);
}
void displayMessage(String prefix, FocusEvent e) {
display.append(prefix
+ (e.isTemporary() ? " (temporary):" : ":")
+ e.getComponent().getClass().getName()
+ "; Opposite component: "
+ (e.getOppositeComponent() != null ? e.getOppositeComponent()
.getClass().getName() : "null") + newline);
display.setCaretPosition(display.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("FocusEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new FocusEventDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Focus Next Component Sample
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class NextComponentSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Next Component Sample");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(3, 3));
int COUNT = 9;
JButton components[] = new JButton[COUNT];
for (int i = 0; i < COUNT; i++) {
JButton button = new JButton("" + (i + 1));
components[i] = button;
contentPane.add(button);
}
for (int i = 0; i < COUNT; i++) {
System.out.println(components[i].getText() + ":" + components[(i + COUNT - 1) % COUNT].getText());
components[i].setNextFocusableComponent(components[(i + COUNT - 1)% COUNT]);
}
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Handle a window closing event
import java.awt.Button;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Main extends JFrame {
public static void main(String[] args) {
Main frame = new Main();
frame.setSize(new Dimension(200, 200));
frame.add(new Button("Hello World"));
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
}
}
Implement a graphical list selection monitor
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class SelectionMonitor extends JPanel {
String label[] = { "1", "2", "3"};
JCheckBox checks[] = new JCheckBox[label.length];
JList list = new JList(label);
public SelectionMonitor() {
JScrollPane pane = new JScrollPane(list);
add(pane);
list.addListSelectionListener(new RadioUpdater());
for (int i = 0; i < label.length; i++) {
checks[i] = new JCheckBox("Selection " + i);
add(checks[i]);
}
}
public static void main(String s[]) {
JFrame frame = new JFrame("Selection Monitor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new SelectionMonitor());
frame.pack();
frame.setVisible(true);
}
}
class RadioUpdater implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
if ((!e.getValueIsAdjusting()) || (e.getFirstIndex() == -1))
return;
for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) {
System.out.println(((JList) e.getSource()).isSelectedIndex(i));
}
}
}
implements VetoableChangeListener to block focus change events
import java.awt.ruponent;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
public class Main {
public static void main(String[] argv) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addVetoableChangeListener(
new FocusVetoableChangeListener());
}
}
class FocusVetoableChangeListener implements VetoableChangeListener {
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
Component oldComp = (Component) evt.getOldValue();
Component newComp = (Component) evt.getNewValue();
if ("focusOwner".equals(evt.getPropertyName())) {
if (oldComp == null) {
System.out.println(newComp.getName());
} else {
System.out.println(oldComp.getName());
}
} else if ("focusedWindow".equals(evt.getPropertyName())) {
if (oldComp == null) {
System.out.println(newComp.getName());
} else {
System.out.println(oldComp.getName());
}
}
boolean vetoFocusChange = false;
if (vetoFocusChange) {
throw new PropertyVetoException("message", evt);
}
}
}
Installs/resets a ComponentListener to resize the given window to minWidth/Height if needed
/*
* $Id: WindowUtils.java,v 1.16 2009/05/25 16:37:52 kschaefe Exp $
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
import java.awt.Window;
import java.awt.event.ruponentAdapter;
import java.awt.event.ruponentListener;
import javax.swing.SwingUtilities;
public class Utils {
/**
* Installs/resets a ComponentListener to resize the
* given window to minWidth/Height if needed.
*
* @param window
* @param minWidth
* @param minHeight
*/
public static void setMinimumSizeManager(Window window, int minWidth,
int minHeight) {
ComponentListener[] listeners = window.getComponentListeners();
ComponentListener listener = null;
for (ComponentListener l : listeners) {
if (l instanceof MinSizeComponentListener) {
listener = l;
break;
}
}
if (listener == null) {
window.addComponentListener(new MinSizeComponentListener(
window, minWidth, minHeight));
} else {
((MinSizeComponentListener) listener).resetSizes(minWidth,
minHeight);
}
}
/**
* Resets window size to minSize if needed.
*
* @author Patrick Wright
*/
public static class MinSizeComponentListener extends ComponentAdapter {
private Window window;
private int minHeight;
private int minWidth;
MinSizeComponentListener(Window frame, int minWidth, int minHeight) {
this.window = frame;
resetSizes(minWidth, minHeight);
}
public void resetSizes(int minWidth, int minHeight) {
this.minWidth = minWidth;
this.minHeight = minHeight;
adjustIfNeeded(window);
}
@Override
public void componentResized(java.awt.event.ruponentEvent evt) {
adjustIfNeeded((Window) evt.getComponent());
}
private void adjustIfNeeded(final Window window) {
boolean doSize = false;
int newWidth = window.getWidth();
int newHeight = window.getHeight();
if (newWidth < minWidth) {
newWidth = minWidth;
doSize = true;
}
if (newHeight < minHeight) {
newHeight = minHeight;
doSize = true;
}
if (doSize) {
final int w = newWidth;
final int h = newHeight;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
window.setSize(w, h);
}
});
}
}
}
}
ItemListener for JRadioButton
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;
public class Main extends JFrame {
private JRadioButton small, medium, large;
private JButton button;
public Main(String title) {
super(title);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container contentPane = this.getContentPane();
ButtonGroup group = new ButtonGroup();
small = new JRadioButton("small");
medium = new JRadioButton("medium");
large = new JRadioButton("large");
group.add(small);
group.add(medium);
group.add(large);
button = new JButton("Click here.");
button.setBounds(100, 50, 100, 50);
JPanel center = new JPanel();
center.setLayout(null);
center.add(button);
contentPane.add(center, BorderLayout.CENTER);
JPanel north = new JPanel();
north.add(small);
north.add(medium);
north.add(large);
contentPane.add(north, BorderLayout.NORTH);
ChangeSize listener = new ChangeSize(button);
small.addItemListener(listener);
medium.addItemListener(listener);
large.addItemListener(listener);
}
public static void main(String[] args) {
JFrame f = new Main("JRadioButtonDemo");
f.setSize(300, 200);
f.setVisible(true);
}
}
class ChangeSize implements ItemListener {
private Component component;
public ChangeSize(Component c) {
component = c;
}
public void itemStateChanged(ItemEvent e) {
String size = (String) e.getItem();
if (size.equals("small")) {
component.setSize(75, 20);
} else if (size.equals("medium")) {
component.setSize(100, 50);
} else if (size.equals("large")) {
component.setSize(150, 75);
}
}
}
JAR Archives: Pack Progress Monitor
import java.awt.ruponent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.jar.Pack200;
import javax.swing.ProgressMonitor;
public class PackProgressMonitor extends ProgressMonitor implements PropertyChangeListener {
public PackProgressMonitor(Component parent) {
super(parent, null, "Packing", -1, 100);
}
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName().equals(Pack200.Packer.PROGRESS)) {
String newValue = (String) event.getNewValue();
int value = Integer.parseInt(newValue);
this.setProgress(value);
}
}
}
KeyListener, ActionListener Demo 1
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.AWTEventMulticaster;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class KeyTextTester {
public static void main(String args[]) {
JFrame frame = new JFrame("Key Text Sample");
KeyTextComponent keyTextComponent = new KeyTextComponent();
final JTextField textField = new JTextField();
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
String keyText = actionEvent.getActionCommand();
textField.setText(keyText);
}
};
keyTextComponent.addActionListener(actionListener);
Container contentPane = frame.getContentPane();
contentPane.add(keyTextComponent, BorderLayout.CENTER);
contentPane.add(textField, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
class KeyTextComponent extends Canvas {
private ActionListener actionListenerList = null;
public KeyTextComponent() {
setBackground(Color.cyan);
KeyListener internalKeyListener = new KeyAdapter() {
public void keyPressed(KeyEvent keyEvent) {
if (actionListenerList != null) {
int keyCode = keyEvent.getKeyCode();
String keyText = KeyEvent.getKeyText(keyCode);
ActionEvent actionEvent = new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, keyText);
actionListenerList.actionPerformed(actionEvent);
}
}
};
MouseListener internalMouseListener = new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
requestFocus();
}
};
addKeyListener(internalKeyListener);
addMouseListener(internalMouseListener);
}
public void addActionListener(ActionListener actionListener) {
actionListenerList = AWTEventMulticaster.add(actionListenerList,
actionListener);
}
public void removeActionListener(ActionListener actionListener) {
actionListenerList = AWTEventMulticaster.remove(actionListenerList,
actionListener);
}
public boolean isFocusTraversable() {
return true;
}
}
KeyListener, ActionListener Demo 2
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.EventListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.EventListenerList;
public class KeyTextTester2 {
public static void main(String args[]) {
JFrame frame = new JFrame("Key Text Sample");
KeyTextComponent2 keyTextComponent = new KeyTextComponent2();
final JTextField textField = new JTextField();
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
String keyText = actionEvent.getActionCommand();
textField.setText(keyText);
}
};
keyTextComponent.addActionListener(actionListener);
Container contentPane = frame.getContentPane();
contentPane.add(keyTextComponent, BorderLayout.CENTER);
contentPane.add(textField, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
class KeyTextComponent2 extends Canvas {
private EventListenerList actionListenerList = new EventListenerList();
public KeyTextComponent2() {
setBackground(Color.cyan);
KeyListener internalKeyListener = new KeyAdapter() {
public void keyPressed(KeyEvent keyEvent) {
if (actionListenerList != null) {
int keyCode = keyEvent.getKeyCode();
String keyText = KeyEvent.getKeyText(keyCode);
ActionEvent actionEvent = new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, keyText);
fireActionPerformed(actionEvent);
}
}
};
MouseListener internalMouseListener = new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
requestFocus();
}
};
addKeyListener(internalKeyListener);
addMouseListener(internalMouseListener);
}
public void addActionListener(ActionListener actionListener) {
actionListenerList.add(ActionListener.class, actionListener);
}
public void removeActionListener(ActionListener actionListener) {
actionListenerList.remove(ActionListener.class, actionListener);
}
protected void fireActionPerformed(ActionEvent actionEvent) {
EventListener listenerList[] = actionListenerList
.getListeners(ActionListener.class);
for (int i = 0, n = listenerList.length; i < n; i++) {
((ActionListener) listenerList[i]).actionPerformed(actionEvent);
}
}
public boolean isFocusTraversable() {
return true;
}
}
KeyStroke Sample
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
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 KeyStrokeSample {
private static final String ACTION_KEY = "theAction";
public static void main(String args[]) {
JFrame frame = new JFrame("KeyStroke Sample");
JButton buttonA = new JButton("<html><center>FOCUSED<br>control alt 7");
JButton buttonB = new JButton("<html><center>FOCUS/RELEASE<br>VK_ENTER");
JButton buttonC = new JButton(
"<html><center>ANCESTOR<br>VK_F4+SHIFT_MASK");
JButton buttonD = new JButton("<html><center>WINDOW<br>" "");
// Define ActionListener
Action actionListener = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
JButton source = (JButton) actionEvent.getSource();
System.out.println("Activated: " + source.getText());
}
};
KeyStroke controlAlt7 = KeyStroke.getKeyStroke("control alt 7");
InputMap inputMap = buttonA.getInputMap();
inputMap.put(controlAlt7, ACTION_KEY);
ActionMap actionMap = buttonA.getActionMap();
actionMap.put(ACTION_KEY, actionListener);
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true);
inputMap = buttonB.getInputMap();
inputMap.put(enter, ACTION_KEY);
buttonB.setActionMap(actionMap);
KeyStroke shiftF4 = KeyStroke.getKeyStroke(KeyEvent.VK_F4,InputEvent.SHIFT_MASK);
inputMap = buttonC.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(shiftF4, ACTION_KEY);
buttonC.setActionMap(actionMap);
KeyStroke space = KeyStroke.getKeyStroke(" ");
inputMap = buttonD.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(space, ACTION_KEY);
buttonD.setActionMap(actionMap);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(2, 2));
contentPane.add(buttonA);
contentPane.add(buttonB);
contentPane.add(buttonC);
contentPane.add(buttonD);
frame.setSize(400, 200);
frame.setVisible(true);
}
}
Load Save Action
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.text.JTextComponent;
import javax.swing.text.html.HTMLEditorKit;
public class LoadSaveAction {
public static void main(String args[]) {
final String filename = "Test.html";
JFrame frame = new JFrame("Loading/Saving Example");
Container content = frame.getContentPane();
final JEditorPane editorPane = new JEditorPane();
JScrollPane scrollPane = new JScrollPane(editorPane);
content.add(scrollPane, BorderLayout.CENTER);
editorPane.setEditorKit(new HTMLEditorKit());
JPanel panel = new JPanel();
Action loadAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
doLoadCommand(editorPane, filename);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
loadAction.putValue(Action.NAME, "Load");
JButton loadButton = new JButton(loadAction);
panel.add(loadButton);
Action saveAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
doSaveCommand(editorPane, filename);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
saveAction.putValue(Action.NAME, "Save");
JButton saveButton = new JButton(saveAction);
panel.add(saveButton);
Action clearAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
editorPane.setText("");
}
};
clearAction.putValue(Action.NAME, "Clear");
JButton clearButton = new JButton(clearAction);
panel.add(clearButton);
content.add(panel, BorderLayout.SOUTH);
frame.setSize(250, 150);
frame.setVisible(true);
}
public static void doSaveCommand(JTextComponent textComponent, String filename) throws Exception{
FileWriter writer = null;
writer = new FileWriter(filename);
textComponent.write(writer);
writer.close();
}
public static void doLoadCommand(JTextComponent textComponent, String filename) throws Exception{
FileReader reader = null;
reader = new FileReader(filename);
textComponent.read(reader, filename);
reader.close();
}
}
PropertyChangeListener Sample
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class BoundSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Button Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton button1 = new JButton("Select Me");
final JButton button2 = new JButton("No Select Me");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
JButton button = (JButton) actionEvent.getSource();
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
button.setBackground(new Color(red, green, blue));
}
};
PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String property = propertyChangeEvent.getPropertyName();
if ("background".equals(property)) {
button2.setBackground((Color) propertyChangeEvent
.getNewValue());
}
}
};
button1.addActionListener(actionListener);
button1.addPropertyChangeListener(propertyChangeListener);
button2.addActionListener(actionListener);
Container contentPane = frame.getContentPane();
contentPane.add(button1, BorderLayout.NORTH);
contentPane.add(button2, BorderLayout.SOUTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
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();
}
}
Show events as they happen
// : c14:TrackEvent.java
// Show events as they happen.
// <applet code=TrackEvent width=700 height=500></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.HashMap;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class TrackEvent extends JApplet {
private HashMap h = new HashMap();
private String[] event = { "focusGained", "focusLost", "keyPressed",
"keyReleased", "keyTyped", "mouseClicked", "mouseEntered",
"mouseExited", "mousePressed", "mouseReleased", "mouseDragged",
"mouseMoved" };
private MyButton b1 = new MyButton(Color.BLUE, "test1"), b2 = new MyButton(
Color.RED, "test2");
class MyButton extends JButton {
void report(String field, String msg) {
((JTextField) h.get(field)).setText(msg);
}
FocusListener fl = new FocusListener() {
public void focusGained(FocusEvent e) {
report("focusGained", e.paramString());
}
public void focusLost(FocusEvent e) {
report("focusLost", e.paramString());
}
};
KeyListener kl = new KeyListener() {
public void keyPressed(KeyEvent e) {
report("keyPressed", e.paramString());
}
public void keyReleased(KeyEvent e) {
report("keyReleased", e.paramString());
}
public void keyTyped(KeyEvent e) {
report("keyTyped", e.paramString());
}
};
MouseListener ml = new MouseListener() {
public void mouseClicked(MouseEvent e) {
report("mouseClicked", e.paramString());
}
public void mouseEntered(MouseEvent e) {
report("mouseEntered", e.paramString());
}
public void mouseExited(MouseEvent e) {
report("mouseExited", e.paramString());
}
public void mousePressed(MouseEvent e) {
report("mousePressed", e.paramString());
}
public void mouseReleased(MouseEvent e) {
report("mouseReleased", e.paramString());
}
};
MouseMotionListener mml = new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
report("mouseDragged", e.paramString());
}
public void mouseMoved(MouseEvent e) {
report("mouseMoved", e.paramString());
}
};
public MyButton(Color color, String label) {
super(label);
setBackground(color);
addFocusListener(fl);
addKeyListener(kl);
addMouseListener(ml);
addMouseMotionListener(mml);
}
}
public void init() {
Container c = getContentPane();
c.setLayout(new GridLayout(event.length + 1, 2));
for (int i = 0; i < event.length; i++) {
JTextField t = new JTextField();
t.setEditable(false);
c.add(new JLabel(event[i], JLabel.RIGHT));
c.add(t);
h.put(event[i], t);
}
c.add(b1);
c.add(b2);
}
public static void main(String[] args) {
run(new TrackEvent(), 700, 500);
}
public static void run(JApplet applet, int width, int height) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(width, height);
applet.init();
applet.start();
frame.setVisible(true);
}
} ///:~
Showing how to add Actions for KeyStrokes
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Hashtable;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;
import javax.swing.text.TextAction;
public class KeymapExample {
public static void main(String[] args) {
JTextArea area = new JTextArea(6, 32);
Keymap parent = area.getKeymap();
Keymap newmap = JTextComponent.addKeymap("KeymapExampleMap", parent);
KeyStroke u = KeyStroke.getKeyStroke(KeyEvent.VK_U,
InputEvent.CTRL_MASK);
Action actionU = new UpWord();
newmap.addActionForKeyStroke(u, actionU);
Action actionList[] = area.getActions();
Hashtable lookup = new Hashtable();
for (int j = 0; j < actionList.length; j += 1)
lookup.put(actionList[j].getValue(Action.NAME), actionList[j]);
KeyStroke L = KeyStroke.getKeyStroke(KeyEvent.VK_L,
InputEvent.CTRL_MASK);
Action actionL = (Action) lookup.get(DefaultEditorKit.selectLineAction);
newmap.addActionForKeyStroke(L, actionL);
KeyStroke W = KeyStroke.getKeyStroke(KeyEvent.VK_W,
InputEvent.CTRL_MASK);
Action actionW = (Action) lookup.get(DefaultEditorKit.selectWordAction);
newmap.addActionForKeyStroke(W, actionW);
area.setKeymap(newmap);
JFrame f = new JFrame("KeymapExample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
area.setText("This is a test.");
f.pack();
f.setVisible(true);
}
}
class UpWord extends TextAction {
public UpWord() {
super("uppercase-word-action");
}
public void actionPerformed(ActionEvent e) {
JTextComponent comp = getTextComponent(e);
if (comp == null)
return;
Document doc = comp.getDocument();
int start = comp.getSelectionStart();
int end = comp.getSelectionEnd();
try {
int left = javax.swing.text.Utilities.getWordStart(comp, start);
int right = javax.swing.text.Utilities.getWordEnd(comp, end);
String word = doc.getText(left, right - left);
doc.remove(left, right - left);
doc.insertString(left, word.toUpperCase(), null);
comp.setSelectionStart(start);
comp.setSelectionEnd(end);
} catch (BadLocationException ble) {
return;
}
}
}
Sketch
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// Sketch.java
//A sketching application with two dials: one for horizontal movement, one
//for vertical movement. The dials are instances of the JogShuttle class.
//
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BoundedRangeModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.ruponentUI;
public class Sketch extends JPanel implements PropertyChangeListener,
ActionListener {
JogShuttle shuttle1;
JogShuttle shuttle2;
JPanel board;
JButton clear;
int lastX, lastY; // Keep track of the last point we drew.
public Sketch() {
super(true);
setLayout(new BorderLayout());
board = new JPanel(true);
board.setPreferredSize(new Dimension(300, 300));
board.setBorder(new LineBorder(Color.black, 5));
clear = new JButton("Clear Drawing Area");
clear.addActionListener(this);
shuttle1 = new JogShuttle(0, 300, 150);
lastX = shuttle1.getValue();
shuttle2 = new JogShuttle(0, 300, 150);
lastY = shuttle2.getValue();
shuttle1.setValuePerRevolution(100);
shuttle2.setValuePerRevolution(100);
shuttle1.addPropertyChangeListener(this);
shuttle2.addPropertyChangeListener(this);
shuttle1.setBorder(new BevelBorder(BevelBorder.RAISED));
shuttle2.setBorder(new BevelBorder(BevelBorder.RAISED));
add(board, BorderLayout.NORTH);
add(shuttle1, BorderLayout.WEST);
add(clear, BorderLayout.CENTER);
add(shuttle2, BorderLayout.EAST);
}
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName() == "value") {
Graphics g = board.getGraphics();
g.setColor(getForeground());
g.drawLine(lastX, lastY, shuttle1.getValue(), shuttle2.getValue());
lastX = shuttle1.getValue();
lastY = shuttle2.getValue();
}
}
public void actionPerformed(ActionEvent e) {
// The button must have been pressed.
Insets insets = board.getInsets();
Graphics g = board.getGraphics();
g.setColor(board.getBackground());
g.fillRect(insets.left, insets.top, board.getWidth() - insets.left
- insets.right, board.getHeight() - insets.top - insets.bottom);
}
public static void main(String[] args) {
UIManager.put(JogShuttleUI.UI_CLASS_ID, "BasicJogShuttleUI");
Sketch s = new Sketch();
JFrame frame = new JFrame("Sample Sketch Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(s);
frame.pack();
frame.setVisible(true);
}
}
//JogShuttle.java
//A custom jog shuttle component. (Some VCRs have such a thing for doing
//variable speed fast-forward and fast-reverse.) An example of using the
//JogShuttle can be found in Sketch.java.
//
class JogShuttle extends JComponent implements ChangeListener {
private BoundedRangeModel model;
// The dialInsets property tells how far the dial is inset
// from the sunken border.
private Insets dialInsets = new Insets(3, 3, 3, 3);
// The valuePerRevolution property tells how many units the dial
// takes to make a complete revolution.
private int valuePerRevolution;
// Constructors
public JogShuttle() {
init(new DefaultBoundedRangeModel());
}
public JogShuttle(BoundedRangeModel m) {
init(m);
}
public JogShuttle(int min, int max, int value) {
init(new DefaultBoundedRangeModel(value, 1, min, max));
}
protected void init(BoundedRangeModel m) {
setModel(m);
valuePerRevolution = m.getMaximum() - m.getMinimum();
setMinimumSize(new Dimension(80, 80));
setPreferredSize(new Dimension(80, 80));
updateUI();
}
public void setUI(JogShuttleUI ui) {
super.setUI(ui);
}
public void updateUI() {
setUI((JogShuttleUI) UIManager.getUI(this));
invalidate();
}
public String getUIClassID() {
return JogShuttleUI.UI_CLASS_ID;
}
public void setModel(BoundedRangeModel m) {
BoundedRangeModel old = model;
if (old != null)
old.removeChangeListener(this);
if (m == null)
model = new DefaultBoundedRangeModel();
else
model = m;
model.addChangeListener(this);
firePropertyChange("model", old, model);
}
public BoundedRangeModel getModel() {
return model;
}
// Methods
public void resetToMinimum() {
model.setValue(model.getMinimum());
}
public void resetToMaximum() {
model.setValue(model.getMaximum());
}
public void stateChanged(ChangeEvent e) {
repaint();
}
// Accessors and mutators
public int getMinimum() {
return model.getMinimum();
}
public void setMinimum(int m) {
int old = getMinimum();
if (m != old) {
model.setMinimum(m);
firePropertyChange("minimum", old, m);
}
}
public int getMaximum() {
return model.getMaximum();
}
public void setMaximum(int m) {
int old = getMaximum();
if (m != old) {
model.setMaximum(m);
firePropertyChange("maximum", old, m);
}
}
public int getValue() {
return model.getValue();
}
public void setValue(int v) {
int old = getValue();
if (v != old) {
model.setValue(v);
firePropertyChange("value", old, v);
}
}
// Display-specific properties
public int getValuePerRevolution() {
return valuePerRevolution;
}
public void setValuePerRevolution(int v) {
int old = getValuePerRevolution();
if (v != old) {
valuePerRevolution = v;
firePropertyChange("valuePerRevolution", old, v);
}
repaint();
}
public void setDialInsets(Insets i) {
dialInsets = i;
}
public void setDialInsets(int top, int left, int bottom, int right) {
dialInsets = new Insets(top, left, bottom, right);
}
public Insets getDialInsets() {
return dialInsets;
}
}
//JogShuttleUI.java
//Fill out the proper UIClassID information for our JogShuttle.
//
abstract class JogShuttleUI extends ComponentUI {
public static final String UI_CLASS_ID = "JogShuttleUI";
}
StateChange Listener
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SelectingButton {
public static void main(String args[]) {
JFrame frame = new JFrame("Selecting Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton theButton = new JButton("Button");
ActionListener aListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
AbstractButton aButton = (AbstractButton) event.getSource();
boolean selected = aButton.getModel().isSelected();
System.out.println("Action - selected=" + selected + "\n");
}
};
ChangeListener cListener = new ChangeListener() {
public void stateChanged(ChangeEvent event) {
AbstractButton aButton = (AbstractButton) event.getSource();
ButtonModel aModel = aButton.getModel();
boolean armed = aModel.isArmed();
boolean pressed = aModel.isPressed();
boolean selected = aModel.isSelected();
System.out.println("Changed: " + armed + "/" + pressed + "/" + selected);
}
};
theButton.addActionListener(aListener);
theButton.addChangeListener(cListener);
Container contentPane = frame.getContentPane();
contentPane.add(theButton, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Swing Action Demo
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
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.ItemListener;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.ruparator;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.Border;
import javax.swing.event.ChangeListener;
import javax.swing.text.JTextComponent;
public class ListActions {
public static void main(String args[]) {
JFrame frame = new JFrame("TextAction List");
Container contentPane = frame.getContentPane();
String components[] = { "JTextField", "JPasswordField", "JTextArea",
"JTextPane", "JEditorPane" };
final JTextArea textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
contentPane.add(scrollPane, BorderLayout.CENTER);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
// Determine which component selected
String command = actionEvent.getActionCommand();
JTextComponent component = null;
if (command.equals("JTextField")) {
component = new JTextField();
} else if (command.equals("JPasswordField")) {
component = new JPasswordField();
} else if (command.equals("JTextArea")) {
component = new JTextArea();
} else if (command.equals("JTextPane")) {
component = new JTextPane();
} else {
component = new JEditorPane();
}
// Process action list
Action actions[] = component.getActions();
// Java 2 specific code to sort
Comparator comparator = new Comparator() {
public int compare(Object a1, Object a2) {
int returnValue = 0;
if ((a1 instanceof Action) && (a2 instanceof Action)) {
String firstName = (String) ((Action) a1)
.getValue(Action.NAME);
String secondName = (String) ((Action) a2)
.getValue(Action.NAME);
returnValue = firstName.rupareTo(secondName);
}
return returnValue;
}
};
Arrays.sort(actions, comparator);
// end Java 2 specific code
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
int count = actions.length;
pw.println("Count: " + count);
for (int i = 0; i < count; i++) {
pw.print(actions[i].getValue(Action.NAME));
pw.print(" : ");
pw.println(actions[i].getClass().getName());
}
pw.close();
textArea.setText(sw.toString());
textArea.setCaretPosition(0);
}
};
final Container componentsContainer = RadioButtonUtils
.createRadioButtonGrouping(components, "Pick to List Actions",
actionListener);
contentPane.add(componentsContainer, BorderLayout.WEST);
frame.setSize(400, 250);
frame.setVisible(true);
}
}
class RadioButtonUtils {
private RadioButtonUtils() {
// private constructor so you can"t create instances
}
public static Enumeration getSelectedElements(Container container) {
Vector selections = new Vector();
Component components[] = container.getComponents();
for (int i = 0, n = components.length; i < n; i++) {
if (components[i] instanceof AbstractButton) {
AbstractButton button = (AbstractButton) components[i];
if (button.isSelected()) {
selections.addElement(button.getText());
}
}
}
return selections.elements();
}
public static Container createRadioButtonGrouping(String elements[]) {
return createRadioButtonGrouping(elements, null, null, null, null);
}
public static Container createRadioButtonGrouping(String elements[],
String title) {
return createRadioButtonGrouping(elements, title, null, null, null);
}
public static Container createRadioButtonGrouping(String elements[],
String title, ItemListener itemListener) {
return createRadioButtonGrouping(elements, title, null, itemListener,
null);
}
public static Container createRadioButtonGrouping(String elements[],
String title, ActionListener actionListener) {
return createRadioButtonGrouping(elements, title, actionListener, null,
null);
}
public static Container createRadioButtonGrouping(String elements[],
String title, ActionListener actionListener,
ItemListener itemListener) {
return createRadioButtonGrouping(elements, title, actionListener,
itemListener, null);
}
public static Container createRadioButtonGrouping(String elements[],
String title, ActionListener actionListener,
ItemListener itemListener, ChangeListener changeListener) {
JPanel panel = new JPanel(new GridLayout(0, 1));
// If title set, create titled border
if (title != null) {
Border border = BorderFactory.createTitledBorder(title);
panel.setBorder(border);
}
// Create group
ButtonGroup group = new ButtonGroup();
JRadioButton aRadioButton;
// For each String passed in:
// Create button, add to panel, and add to group
for (int i = 0, n = elements.length; i < n; i++) {
aRadioButton = new JRadioButton(elements[i]);
panel.add(aRadioButton);
group.add(aRadioButton);
if (actionListener != null) {
aRadioButton.addActionListener(actionListener);
}
if (itemListener != null) {
aRadioButton.addItemListener(itemListener);
}
if (changeListener != null) {
aRadioButton.addChangeListener(changeListener);
}
}
return panel;
}
}
TextAction example
//A simple TextAction example.
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextArea;
public class TextActionExample {
public static void main(String[] args) {
JTextArea ta = new JTextArea();
ta.setLineWrap(true);
Action[] actions = ta.getActions();
JMenuBar menubar = new JMenuBar();
JMenu actionmenu = new JMenu("Actions");
menubar.add(actionmenu);
JMenu firstHalf = new JMenu("1st Half");
JMenu secondHalf = new JMenu("2nd Half");
actionmenu.add(firstHalf);
actionmenu.add(secondHalf);
int mid = actions.length / 2;
for (int i = 0; i < mid; i++) {
firstHalf.add(actions[i]);
}
for (int i = mid; i < actions.length; i++) {
secondHalf.add(actions[i]);
}
// Show it . . .
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(ta);
f.setJMenuBar(menubar);
f.setSize(300, 200);
f.setVisible(true);
}
}
Timer Sample
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class TimerSample {
public static void main(String args[]) {
new JFrame().setVisible(true);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Hello World Timer");
}
};
Timer timer = new Timer(500, actionListener);
timer.start();
}
}
Using ComponentListener to catch the JFrame Maximization event
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ruponentEvent;
import java.awt.event.ruponentListener;
import javax.swing.JFrame;
public class Main extends JFrame implements ComponentListener {
public Main() {
addComponentListener(this);
}
public void componentHidden(ComponentEvent e) {
System.out.println("componentHidden");
}
public void componentMoved(ComponentEvent e) {
System.out.println("componentMoved");
}
public void componentResized(ComponentEvent e) {
System.out.println("componentResized");
if (getState() == Frame.ICONIFIED) {
System.out.println("RESIZED TO ICONIFIED");
} else if (getState() == Frame.NORMAL) {
System.out.println("RESIZED TO NORMAL");
} else {
System.out.println("RESIZED TO MAXIMIZED");
}
}
public void componentShown(ComponentEvent e) {
}
public static void main(String[] arg) {
Main m = new Main();
m.setVisible(true);
m.setSize(new Dimension(300, 100));
m.setLocation(50, 50);
}
}
Window Event Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* WindowEventDemo.java is a 1.4 example that requires no other files.
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
public class WindowEventDemo extends JPanel implements WindowListener,
WindowFocusListener, WindowStateListener {
final static String newline = "\n";
final static String space = " ";
static JFrame frame;
JTextArea display;
public WindowEventDemo() {
super(new BorderLayout());
display = new JTextArea();
display.setEditable(false);
JScrollPane scrollPane = new JScrollPane(display);
scrollPane.setPreferredSize(new Dimension(500, 450));
add(scrollPane, BorderLayout.CENTER);
frame.addWindowListener(this);
frame.addWindowFocusListener(this);
frame.addWindowStateListener(this);
checkWM();
}
//Some window managers don"t support all window states.
//For example, dtwm doesn"t support true maximization,
//but mimics it by resizing the window to be the size
//of the screen. In this case the window does not fire
//the MAXIMIZED_ constants on the window"s state listener.
//Microsoft Windows supports MAXIMIZED_BOTH, but not
//MAXIMIZED_VERT or MAXIMIZED_HORIZ.
public void checkWM() {
Toolkit tk = frame.getToolkit();
if (!(tk.isFrameStateSupported(Frame.ICONIFIED))) {
displayMessage("Your window manager doesn"t support ICONIFIED.");
}
if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_VERT))) {
displayMessage("Your window manager doesn"t support MAXIMIZED_VERT.");
}
if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_HORIZ))) {
displayMessage("Your window manager doesn"t support MAXIMIZED_HORIZ.");
}
if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_BOTH))) {
displayMessage("Your window manager doesn"t support MAXIMIZED_BOTH.");
} else {
displayMessage("Your window manager supports MAXIMIZED_BOTH.");
}
}
public void windowClosing(WindowEvent e) {
displayMessage("WindowListener method called: windowClosing.");
//A pause so user can see the message before
//the window actually closes.
ActionListener task = new ActionListener() {
boolean alreadyDisposed = false;
public void actionPerformed(ActionEvent e) {
if (!alreadyDisposed) {
alreadyDisposed = true;
frame.dispose();
} else { //make sure the program exits
System.exit(0);
}
}
};
Timer timer = new Timer(500, task); //fire every half second
timer.setInitialDelay(2000); //first delay 2 seconds
timer.start();
}
public void windowClosed(WindowEvent e) {
//This will only be seen on standard output.
displayMessage("WindowListener method called: windowClosed.");
}
public void windowOpened(WindowEvent e) {
displayMessage("WindowListener method called: windowOpened.");
}
public void windowIconified(WindowEvent e) {
displayMessage("WindowListener method called: windowIconified.");
}
public void windowDeiconified(WindowEvent e) {
displayMessage("WindowListener method called: windowDeiconified.");
}
public void windowActivated(WindowEvent e) {
displayMessage("WindowListener method called: windowActivated.");
}
public void windowDeactivated(WindowEvent e) {
displayMessage("WindowListener method called: windowDeactivated.");
}
public void windowGainedFocus(WindowEvent e) {
displayMessage("WindowFocusListener method called: windowGainedFocus.");
}
public void windowLostFocus(WindowEvent e) {
displayMessage("WindowFocusListener method called: windowLostFocus.");
}
public void windowStateChanged(WindowEvent e) {
displayStateMessage(
"WindowStateListener method called: windowStateChanged.", e);
}
void displayMessage(String msg) {
display.append(msg + newline);
System.out.println(msg);
}
void displayStateMessage(String prefix, WindowEvent e) {
int state = e.getNewState();
int oldState = e.getOldState();
String msg = prefix + newline + space + "New state: "
+ convertStateToString(state) + newline + space + "Old state: "
+ convertStateToString(oldState);
display.append(msg + newline);
System.out.println(msg);
}
String convertStateToString(int state) {
if (state == Frame.NORMAL) {
return "NORMAL";
}
if ((state & Frame.ICONIFIED) != 0) {
return "ICONIFIED";
}
//MAXIMIZED_BOTH is a concatenation of two bits, so
//we need to test for an exact match.
if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
return "MAXIMIZED_BOTH";
}
if ((state & Frame.MAXIMIZED_VERT) != 0) {
return "MAXIMIZED_VERT";
}
if ((state & Frame.MAXIMIZED_HORIZ) != 0) {
return "MAXIMIZED_HORIZ";
}
return "UNKNOWN";
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
frame = new JFrame("WindowEventDemo");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new WindowEventDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}