/**
*
*/
package de.tutorials;
import java.awt.Color;
import java.awt.ContainerOrderFocusTraversalPolicy;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
/**
* @author Tom
*/
public class JPanelCyclicSelectionExample extends JFrame {
private JPanel[] panels;
private JPanel containerPanel;
public JPanelCyclicSelectionExample() {
super("JPanelCyclicSelectionExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
containerPanel = new JPanel();
containerPanel.setLayout(new GridLayout(1, 4));
Dimension d = new Dimension(80, 240);
panels = new JPanel[4];
FocusListener focusListener = new FocusAdapter() {
public void focusGained(FocusEvent e) {
((JPanel)e.getSource()).setBackground(Color.RED);
}
public void focusLost(FocusEvent e) {
((JPanel)e.getSource()).setBackground(Color.GRAY);
}
};
for (int i = 0; i < panels.length; i++) {
final JPanel panel = panels[i] = new JPanel();
panel.setPreferredSize(d);
panel.addFocusListener(focusListener);
containerPanel.add(panel);
}
Set focusForwardTraversalKeys = new HashSet() {
{
add(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
}
};
Set focusBackwardTraversalKeys = new HashSet() {
{
add(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
}
};
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
focusForwardTraversalKeys);
setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
focusBackwardTraversalKeys);
containerPanel.setFocusCycleRoot(true);
setFocusTraversalPolicy(new ContainerOrderFocusTraversalPolicy());
add(containerPanel);
pack();
setVisible(true);
panels[0].requestFocus();
}
/**
* @param args
*/
public static void main(String[] args) {
new JPanelCyclicSelectionExample();
}
}