《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Test extends JApplet {
public void init() {
Container contentPane = getContentPane();
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.add(new UnderlineElement("item one"));
fileMenu.add(new UnderlineElement("item two"));
fileMenu.add(new UnderlineElement("item three"));
menuBar.add(fileMenu);
setJMenuBar(menuBar);
}
}
class UnderlineElement extends JButton implements MenuElement {
private boolean drawUnderline = false;
public UnderlineElement(String s) {
super(s);
setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
}
public Component getComponent() {
return this;
}
public MenuElement[] getSubElements() {
return new MenuElement[0];
}
public void menuSelectionChanged(boolean b) {
drawUnderline = b;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Insets insets = getInsets();
if(drawUnderline) {
FontMetrics fm = g.getFontMetrics();
g.drawLine(insets.left, insets.top + fm.getHeight(),
fm.stringWidth(getText()),
insets.top + fm.getHeight());
}
}
public void processKeyEvent(KeyEvent me,
MenuElement[] element,
MenuSelectionManager msm) {
}
public void processMouseEvent(MouseEvent me) {
super.processMouseEvent(me);
MenuSelectionManager.defaultManager().processMouseEvent(
me);
}
public void processMouseEvent(MouseEvent me,
MenuElement[] element,
MenuSelectionManager msm) {
if(me.getID() == MouseEvent.MOUSE_CLICKED ||
me.getID() == MouseEvent.MOUSE_RELEASED) {
msm.setSelectedPath(null);
doClick();
}
else
msm.setSelectedPath(getPath());
}
public MenuElement[] getPath() {
MenuSelectionManager defaultManager =
MenuSelectionManager.defaultManager();
MenuElement oldPath[] = defaultManager.getSelectedPath();
MenuElement newPath[];
int len = oldPath.length;
if(len > 0) {
MenuElement lastElement = oldPath[len-1];
Component parent = getParent();
if (lastElement == parent) {
newPath = new MenuElement[len+1];
System.arraycopy(oldPath, 0, newPath, 0, len);
newPath[len] = this;
}
else {
int j;
for (j = len-1; j >= 0; j--) {
if (oldPath[j].getComponent() == parent)
break;
}
newPath = new MenuElement[j+2];
System.arraycopy(oldPath, 0, newPath, 0, j+1);
newPath[j+1] = this;
}
}
else
return new MenuElement[0];
return newPath;
}
}