import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicComboPopup;
public class ComboExample extends JFrame {
private JComboBox combo;
private JPopupMenu myPopup;
public ComboExample() {
super("ComboExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
combo = new JComboBox(new Object[] { "Thomas", "Richard", "Darimont" });
final BasicComboPopup popup = (BasicComboPopup) combo
.getAccessibleContext().getAccessibleChild(0);
myPopup = new JPopupMenu("MyPopupMenu");
getContentPane().add(combo);
pack();
setVisible(true);
final JList list = popup.getList();
final MouseMoveActionHandler handler = new MouseMoveActionHandler();
list.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
if (SwingUtilities.isRightMouseButton(evt)) {
Point p = evt.getPoint();
Point onScreen = combo.getLocationOnScreen();
p.x += onScreen.x;
p.y += onScreen.y;
myPopup.setLocation(p);
final JMenuItem item = myPopup.add(list.getSelectedValue()
.toString());
final JMenuItem item0 = myPopup.add(list.getSelectedValue()
.toString()
+ " getLetterCount");
item.addActionListener(handler);
item.addMouseMotionListener(handler);
item.setRolloverEnabled(true);
handler.map.put(item, new Runnable() {
public void run() {
System.out.println(item.getText());
myPopup.setVisible(false);
myPopup.removeAll();
}
});
item0.addActionListener(handler);
item0.addMouseMotionListener(handler);
item0.setRolloverEnabled(true);
handler.map.put(item0, new Runnable() {
public void run() {
System.out.println(item.getText().length());
myPopup.setVisible(false);
myPopup.removeAll();
}
});
myPopup.requestFocus();
myPopup.setVisible(true);
}
}
});
}
public static void main(String[] args) {
new ComboExample();
}
class MouseMoveActionHandler extends MouseMotionAdapter implements
ActionListener {
protected Map map = new HashMap();
public void mouseMoved(MouseEvent evt) {
Object src = evt.getSource();
if (src instanceof JMenuItem) {
JMenuItem item = (JMenuItem) src;
Component[] components = myPopup.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] != item) {
components[i].setBackground(Color.WHITE);
}
}
item.setBackground(Color.GRAY); //Hier vielleicht noch die
// passende Farbe
// heraussuchen...
item.updateUI();
}
}
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
Runnable runnable = (Runnable) map.get(src);
if (runnable != null) {
runnable.run();
}
}
}
};