Java by API/javax.swing/JComponent — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 14:18, 31 мая 2010
Содержание
- 1 JComponent: addPropertyChangeListener(PropertyChangeListener listener)
- 2 JComponent: addVetoableChangeListener(VetoableChangeListener listener)
- 3 JComponent: getAccessibleContext()
- 4 JComponent: getActionMap()
- 5 JComponent: getHeight()
- 6 JComponent: getInputMap()
- 7 JComponent: getTransferHandler()
- 8 JComponent: getWidth()
- 9 JComponent: getX()
- 10 JComponent: getY()
- 11 JComponent: putClientProperty(Object key, Object value)
- 12 JComponent: registerKeyboardAction(ActionListener anAction, KeyStroke aKeyStroke, int aCondition)
- 13 JComponent: requestFocusInWindow()
- 14 JComponent: revalidate()
- 15 JComponent: setComponentPopupMenu(JPopupMenu popup)
- 16 JComponent: setFocusTraversalKeys(int arg0, Set<? extends AWTKeyStroke> arg1)
- 17 JComponent: setFont(Font font)
- 18 JComponent: setInputMap(int condition, InputMap map)
- 19 JComponent: setInputVerifier(InputVerifier inputVerifier)
- 20 JComponent: setOpaque(boolean isOpaque)
- 21 JComponent: setTransferHandler(TransferHandler newHandler)
- 22 JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
- 23 JComponent.WHEN_IN_FOCUSED_WINDOW
JComponent: addPropertyChangeListener(PropertyChangeListener listener)
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
class ActionChangedListener implements PropertyChangeListener {
private JButton button;
public ActionChangedListener(JButton button) {
this.button = button;
}
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
System.out.println(propertyName);
if (e.getPropertyName().equals(Action.NAME)) {
String text = (String) e.getNewValue();
button.setText(text);
button.repaint();
} else if (propertyName.equals("enabled")) {
Boolean enabledState = (Boolean) e.getNewValue();
button.setEnabled(enabledState.booleanValue());
button.repaint();
} else if (e.getPropertyName().equals(Action.SMALL_ICON)) {
Icon icon = (Icon) e.getNewValue();
button.setIcon(icon);
button.invalidate();
button.repaint();
}
}
}
public class Main {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton bn = new JButton();
bn.addPropertyChangeListener(new ActionChangedListener(bn));
frame.add(bn);
bn.setEnabled(false);
frame.setSize(300, 300);
frame.setVisible(true);
frame.add(bn);
}
}
JComponent: addVetoableChangeListener(VetoableChangeListener listener)
import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
public class MainClass {
public static void main(final String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JDesktopPane desktop = new JDesktopPane();
JInternalFrame palette = new JInternalFrame("Palette", true, true, true,
true);
palette.addVetoableChangeListener(new IconPolice());
palette.setBounds(350, 150, 100, 100);
desktop.add(palette, JDesktopPane.PALETTE_LAYER);
palette.setVisible(true);
frame.add(desktop, BorderLayout.CENTER);
frame.setSize(500, 300);
frame.setVisible(true);
}
}
class IconPolice implements VetoableChangeListener {
public void vetoableChange(PropertyChangeEvent ev) throws PropertyVetoException {
String name = ev.getPropertyName();
if (name.equals(JInternalFrame.IS_ICON_PROPERTY) && (ev.getNewValue() == Boolean.TRUE)) {
System.out.println("JInternalFrame.IS_ICON_PROPERTY");
}
}
}
JComponent: getAccessibleContext()
import java.awt.Dimension;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRelation;
import javax.accessibility.AccessibleRelationSet;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainClass extends JFrame {
MainClass() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
p.setPreferredSize(new Dimension(300, 50));
JLabel jl = new JLabel("Name:");
p.add(jl);
JTextField jtf = new JTextField(20);
jtf.getAccessibleContext().setAccessibleName("Name-entry");
p.add(jtf);
AccessibleRelation ar = new AccessibleRelation("connector", jtf);
AccessibleContext ac = jl.getAccessibleContext();
ac.getAccessibleRelationSet().add(ar);
getContentPane().add(p);
pack();
setVisible(true);
}
public static void main(String[] args) {
MainClass ad11 = new MainClass();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
ad11.dumpConnectedInfo(ad11.getAccessibleContext());
}
void dumpConnectedInfo(AccessibleContext ac) {
AccessibleRelationSet ars = ac.getAccessibleRelationSet();
AccessibleRelation ar = null;
if (ars != null)
ar = ars.get("connector");
if (ar != null) {
Object[] o = ar.getTarget();
JComponent jc = (JComponent) o[0];
System.out.println("Label connected to: " + jc.getAccessibleContext().getAccessibleName());
return;
}
int nChildren = ac.getAccessibleChildrenCount();
for (int i = 0; i < nChildren; i++)
dumpConnectedInfo(ac.getAccessibleChild(i).getAccessibleContext());
}
}
JComponent: getActionMap()
import java.awt.ruponent;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
public static void main(String[] argv) {
JButton component = new JButton();
NextFocusAction nextFocusAction = new NextFocusAction();
component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("SPACE"),
nextFocusAction.getValue(Action.NAME));
component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("F2"),
nextFocusAction.getValue(Action.NAME));
component.getActionMap().put(nextFocusAction.getValue(Action.NAME), nextFocusAction);
}
}
class NextFocusAction extends AbstractAction {
public NextFocusAction() {
super("Move Focus Forwards");
}
public void actionPerformed(ActionEvent evt) {
((Component) evt.getSource()).transferFocus();
}
}
JComponent: getHeight()
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
public class Main extends JFrame {
JComponent comp = new JLabel("Test label");
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
comp.setToolTipText("Some tooltip text for component");
comp.setBorder(new TitledBorder("Button"));
System.out.println("X:" + comp.getX() + " Y:" + comp.getY() + " width:"
+ comp.getWidth() + " height:" + comp.getHeight());
getContentPane().add(comp);
pack();
System.out.println("X:" + comp.getX() + " Y:" + comp.getY() + " width:"
+ comp.getWidth() + " height:" + comp.getHeight());
setVisible(true);
}
public static void main(String arg[]) {
new Main();
}
}
JComponent: getInputMap()
import java.awt.Event;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.DefaultEditorKit;
public class MainClass extends JFrame {
MainClass(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
JLabel jl = new JLabel("Name:");
jp.add(jl);
JTextField jt = new JTextField(20);
jp.add(jt);
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK);
jt.getInputMap().put(ks, DefaultEditorKit.beepAction);
getContentPane().add(jp);
pack();
setVisible(true);
}
public static void main(String[] args) {
new MainClass("Binding Demo2");
}
}
JComponent: getTransferHandler()
/**
* Demonstrate various aspects of Swing "data transfer".
* @author Ian Darwin, http://www.darwinsys.ru
* @author Jonathan Fuerth, http://www.SQLPower.ca
*/
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.TransferHandler;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MainClass extends JFrame {
public static void main(String[] args) {
new MainClass().setVisible(true);
}
private JTextField tf;
private JLabel l;
private JComboBox propertyComboBox;
public MainClass() {
Container cp = new Box(BoxLayout.X_AXIS);
setContentPane(cp);
JPanel firstPanel = new JPanel();
propertyComboBox = new JComboBox();
propertyComboBox.addItem("text");
propertyComboBox.addItem("font");
propertyComboBox.addItem("background");
propertyComboBox.addItem("foreground");
firstPanel.add(propertyComboBox);
cp.add(firstPanel);
cp.add(Box.createGlue());
tf = new JTextField("Hello");
tf.setForeground(Color.RED);
tf.setDragEnabled(true);
cp.add(tf);
cp.add(Box.createGlue());
l = new JLabel("Hello");
l.setBackground(Color.YELLOW);
cp.add(l);
cp.add(Box.createGlue());
JSlider stryder = new JSlider(SwingConstants.VERTICAL);
stryder.setMinimum(10);
stryder.setValue(14);
stryder.setMaximum(72);
stryder.setMajorTickSpacing(10);
stryder.setPaintTicks(true);
cp.add(stryder);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 300);
setMyTransferHandlers((String) propertyComboBox.getSelectedItem());
MouseListener myDragListener = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
};
l.addMouseListener(myDragListener);
propertyComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ce) {
JComboBox bx = (JComboBox) ce.getSource();
String prop = (String) bx.getSelectedItem();
setMyTransferHandlers(prop);
}
});
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JTextField jtf = (JTextField) evt.getSource();
String fontName = jtf.getText();
Font font = new Font(fontName, Font.BOLD, 18);
tf.setFont(font);
}
});
stryder.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
JSlider sl = (JSlider) evt.getSource();
Font oldf = tf.getFont();
Font newf = oldf.deriveFont((float) sl.getValue());
tf.setFont(newf);
}
});
}
private void setMyTransferHandlers(String s) {
TransferHandler th = new TransferHandler(s);
tf.setTransferHandler(th);
l.setTransferHandler(th);
}
}
JComponent: getWidth()
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
public class Main extends JFrame {
JComponent comp = new JLabel("Test label");
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
comp.setToolTipText("Some tooltip text for component");
comp.setBorder(new TitledBorder("Button"));
System.out.println("X:" + comp.getX() + " Y:" + comp.getY() + " width:"
+ comp.getWidth() + " height:" + comp.getHeight());
getContentPane().add(comp);
pack();
System.out.println("X:" + comp.getX() + " Y:" + comp.getY() + " width:"
+ comp.getWidth() + " height:" + comp.getHeight());
setVisible(true);
}
public static void main(String arg[]) {
new Main();
}
}
JComponent: getX()
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
public class Main extends JFrame {
JComponent comp = new JLabel("Test label");
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
comp.setToolTipText("Some tooltip text for component");
comp.setBorder(new TitledBorder("Button"));
System.out.println("X:" + comp.getX() + " Y:" + comp.getY() + " width:"
+ comp.getWidth() + " height:" + comp.getHeight());
getContentPane().add(comp);
pack();
System.out.println("X:" + comp.getX() + " Y:" + comp.getY() + " width:"
+ comp.getWidth() + " height:" + comp.getHeight());
setVisible(true);
}
public static void main(String arg[]) {
new Main();
}
}
JComponent: getY()
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
public class Main extends JFrame {
JComponent comp = new JLabel("Test label");
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
comp.setToolTipText("Some tooltip text for component");
comp.setBorder(new TitledBorder("Button"));
System.out.println("X:" + comp.getX() + " Y:" + comp.getY() + " width:"
+ comp.getWidth() + " height:" + comp.getHeight());
getContentPane().add(comp);
pack();
System.out.println("X:" + comp.getX() + " Y:" + comp.getY() + " width:"
+ comp.getWidth() + " height:" + comp.getHeight());
setVisible(true);
}
public static void main(String arg[]) {
new Main();
}
}
JComponent: putClientProperty(Object key, Object value)
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JSlider;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame("Tick Slider");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSlider oneJSlider = new JSlider();
oneJSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE);
JSlider anotherJSlider = new JSlider();
// Set to default setting
anotherJSlider.putClientProperty("JSlider.isFilled", Boolean.FALSE);
frame.add(oneJSlider, BorderLayout.NORTH);
frame.add(anotherJSlider, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
JComponent: registerKeyboardAction(ActionListener anAction, KeyStroke aKeyStroke, int aCondition)
import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame("Popup Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPopupMenu popup = new JPopupMenu();
JMenuItem menuItem1 = new JMenuItem("Option 1");
popup.add(menuItem1);
JMenuItem menuItem2 = new JMenuItem("Option 2");
popup.add(menuItem2);
final JTextField textField = new JTextField();
frame.add(textField, BorderLayout.NORTH);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
int dotPosition = textField.getCaretPosition();
Rectangle popupLocation = textField.modelToView(dotPosition);
popup.show(textField, popupLocation.x, popupLocation.y);
} catch (BadLocationException badLocationException) {
System.err.println("Oops");
}
}
};
KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, false);
textField.registerKeyboardAction(actionListener, keystroke, JComponent.WHEN_FOCUSED);
frame.add(new JLabel("Press "." to activate Popup menu"), BorderLayout.SOUTH);
frame.setSize(250, 150);
frame.setVisible(true);
}
}
JComponent: requestFocusInWindow()
import java.awt.BorderLayout;
import java.awt.Color;
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.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.EventListenerList;
public class MainClass {
public static void main(String args[]) {
JFrame frame = new JFrame("Key Text Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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);
frame.add(keyTextComponent, BorderLayout.CENTER);
frame.add(textField, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
class KeyTextComponent extends JComponent {
private EventListenerList actionListenerList = new EventListenerList();
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);
fireActionPerformed(actionEvent);
}
}
};
MouseListener internalMouseListener = new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
requestFocusInWindow();
}
};
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 isFocusable() {
return true;
}
}
JComponent: revalidate()
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainClass extends JFrame {
public MainClass() {
super("Revalidation Demo");
setSize(300, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Font font = new Font("Dialog", Font.PLAIN, 10);
final JButton b = new JButton("Add");
b.setFont(font);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(b);
b.addActionListener(new ActionListener() {
int size = 10;
public void actionPerformed(ActionEvent ev) {
b.setFont(new Font("Dialog", Font.PLAIN, ++size));
b.revalidate();
}
});
}
public static void main(String[] args) {
MainClass re = new MainClass();
re.setVisible(true);
}
}
JComponent: setComponentPopupMenu(JPopupMenu popup)
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
class MyPopupMenuListener implements PopupMenuListener {
public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
System.out.println("Canceled");
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Invisible");
}
public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Visible");
}
}
public class Main {
public static void main(final String args[]) {
JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPopupMenu popupMenu = new JPopupMenu("Title");
PopupMenuListener popupMenuListener = new MyPopupMenuListener();
popupMenu.addPopupMenuListener(popupMenuListener);
JMenuItem cutMenuItem = new JMenuItem("Cut");
popupMenu.add(cutMenuItem);
JMenuItem copyMenuItem = new JMenuItem("Copy");
popupMenu.add(copyMenuItem);
JMenuItem pasteMenuItem = new JMenuItem("Paste");
pasteMenuItem.setEnabled(false);
popupMenu.add(pasteMenuItem);
popupMenu.addSeparator();
JMenuItem findMenuItem = new JMenuItem("Find");
popupMenu.add(findMenuItem);
JButton label = new JButton();
frame.add(label);
label.setComponentPopupMenu(popupMenu);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
JComponent: setFocusTraversalKeys(int arg0, Set<? extends AWTKeyStroke> arg1)
import java.awt.AWTKeyStroke;
import java.awt.KeyboardFocusManager;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.KeyStroke;
public class Main {
public static void main(String[] argv) throws Exception {
JButton component = new JButton("a");
Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>(component
.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
set.add(KeyStroke.getKeyStroke("F2"));
component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
}
}
JComponent: setFont(Font font)
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String args[]) {
JFrame f = new JFrame("JColorChooser Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton button = new JButton("Pick to Change Background");
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 12);
button.setFont(myFont);
f.add(button, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
}
}
JComponent: setInputMap(int condition, InputMap map)
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
public static void main(String[] argv) throws Exception {
InputMap inputMap = new InputMap();
inputMap.put(KeyStroke.getKeyStroke("F2"), "actionName");
JButton component = new JButton("button");
inputMap.setParent(component.getInputMap(JComponent.WHEN_FOCUSED));
component.setInputMap(JComponent.WHEN_FOCUSED, inputMap);
}
}
JComponent: setInputVerifier(InputVerifier inputVerifier)
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame("Verifier Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField1 = new JTextField();
JTextField textField2 = new JTextField();
JTextField textField3 = new JTextField();
InputVerifier verifier = new InputVerifier() {
public boolean verify(JComponent comp) {
boolean returnValue;
JTextField textField = (JTextField) comp;
try {
Integer.parseInt(textField.getText());
returnValue = true;
} catch (NumberFormatException e) {
returnValue = false;
}
return returnValue;
}
};
textField1.setInputVerifier(verifier);
textField3.setInputVerifier(verifier);
Container contentPane = frame.getContentPane();
contentPane.add(textField1, BorderLayout.NORTH);
contentPane.add(textField2, BorderLayout.CENTER);
contentPane.add(textField3, BorderLayout.SOUTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
JComponent: setOpaque(boolean isOpaque)
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JFrame {
public MainClass() {
super("Opaque JPanel Demo");
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel opaque = createNested(true);
JPanel notOpaque = createNested(false);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(opaque);
getContentPane().add(notOpaque);
}
public static void main(String[] args) {
MainClass oe = new MainClass();
oe.setVisible(true);
}
public JPanel createNested(boolean opaque) {
JPanel outer = new JPanel(new FlowLayout());
JPanel inner = new JPanel(new FlowLayout());
outer.setBackground(Color.white);
inner.setBackground(Color.black);
inner.setOpaque(opaque);
inner.setBorder(BorderFactory.createLineBorder(Color.gray));
inner.add(new JButton("Button"));
outer.add(inner);
return outer;
}
}
JComponent: setTransferHandler(TransferHandler newHandler)
/**
* Demonstrate various aspects of Swing "data transfer".
* @author Ian Darwin, http://www.darwinsys.ru
* @author Jonathan Fuerth, http://www.SQLPower.ca
*/
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.TransferHandler;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MainClass extends JFrame {
public static void main(String[] args) {
new MainClass().setVisible(true);
}
private JTextField tf;
private JLabel l;
private JComboBox propertyComboBox;
public MainClass() {
Container cp = new Box(BoxLayout.X_AXIS);
setContentPane(cp);
JPanel firstPanel = new JPanel();
propertyComboBox = new JComboBox();
propertyComboBox.addItem("text");
propertyComboBox.addItem("font");
propertyComboBox.addItem("background");
propertyComboBox.addItem("foreground");
firstPanel.add(propertyComboBox);
cp.add(firstPanel);
cp.add(Box.createGlue());
tf = new JTextField("Hello");
tf.setForeground(Color.RED);
tf.setDragEnabled(true);
cp.add(tf);
cp.add(Box.createGlue());
l = new JLabel("Hello");
l.setBackground(Color.YELLOW);
cp.add(l);
cp.add(Box.createGlue());
JSlider stryder = new JSlider(SwingConstants.VERTICAL);
stryder.setMinimum(10);
stryder.setValue(14);
stryder.setMaximum(72);
stryder.setMajorTickSpacing(10);
stryder.setPaintTicks(true);
cp.add(stryder);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 300);
setMyTransferHandlers((String) propertyComboBox.getSelectedItem());
MouseListener myDragListener = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
};
l.addMouseListener(myDragListener);
propertyComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ce) {
JComboBox bx = (JComboBox) ce.getSource();
String prop = (String) bx.getSelectedItem();
setMyTransferHandlers(prop);
}
});
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JTextField jtf = (JTextField) evt.getSource();
String fontName = jtf.getText();
Font font = new Font(fontName, Font.BOLD, 18);
tf.setFont(font);
}
});
stryder.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
JSlider sl = (JSlider) evt.getSource();
Font oldf = tf.getFont();
Font newf = oldf.deriveFont((float) sl.getValue());
tf.setFont(newf);
}
});
}
private void setMyTransferHandlers(String s) {
TransferHandler th = new TransferHandler(s);
tf.setTransferHandler(th);
l.setTransferHandler(th);
}
}
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
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 MainClass {
public static void main(String args[]) {
String ACTION_KEY = "The Action";
JFrame frame = new JFrame("KeyStroke Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton buttonA = new JButton("FOCUSED (control alt 7)");
JButton buttonB = new JButton("FOCUS/RELEASE (VK_ENTER)");
JButton buttonC = new JButton("ANCESTOR (VK_F4+SHIFT_MASK)");
JButton buttonD = new JButton("WINDOW (" ")");
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);
frame.setLayout(new GridLayout(2, 2));
frame.add(buttonA);
frame.add(buttonB);
frame.add(buttonC);
frame.add(buttonD);
frame.setSize(400, 200);
frame.setVisible(true);
}
}
JComponent.WHEN_IN_FOCUSED_WINDOW
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 MainClass {
public static void main(String args[]) {
String ACTION_KEY = "The Action";
JFrame frame = new JFrame("KeyStroke Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton buttonA = new JButton("FOCUSED (control alt 7)");
JButton buttonB = new JButton("FOCUS/RELEASE (VK_ENTER)");
JButton buttonC = new JButton("ANCESTOR (VK_F4+SHIFT_MASK)");
JButton buttonD = new JButton("WINDOW (" ")");
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);
frame.setLayout(new GridLayout(2, 2));
frame.add(buttonA);
frame.add(buttonB);
frame.add(buttonC);
frame.add(buttonD);
frame.setSize(400, 200);
frame.setVisible(true);
}
}