第10章 菜单和工具条(二)

 

10.6.5 JMenu类总结

 

10-14 显示一个菜单条中菜单的信息

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
public void init() {
Container contentPane = getContentPane();

final JMenuBar mb = new JMenuBar();
final MenuBarPrinter printer = new MenuBarPrinter();

JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenuItem exitItem = new JMenuItem("Exit");

fileMenu.setMnemonic('F');
editMenu.setMnemonic('F');

fileMenu.add("New ...");
fileMenu.add("Open ...");
fileMenu.add("Save");
fileMenu.add("Save As ..");
fileMenu.addSeparator();
fileMenu.add(exitItem);

editMenu.add("Cut");
editMenu.add("Copy");
editMenu.add("Paste");

mb.add(fileMenu);
mb.add(editMenu);
setJMenuBar(mb);

JButton button = new JButton("show menu information");
contentPane.setLayout(new FlowLayout());
contentPane.add(button);

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
printer.print(mb);
}
});

exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
class MenuBarPrinter {
static public void print(JMenuBar menubar) {
int numMenus = menubar.getMenuCount();
JMenu nextMenu;

JMenuItem nextItem;

System.out.println();
System.out.println("MenuBar has " +
menubar.getMenuCount() +
" menus");
System.out.println();

for(int i=0; i < numMenus; ++i) {
nextMenu = menubar.getMenu(i);
System.out.println(nextMenu.getText() + " menu ...");
System.out.println(nextMenu);

int numItems = nextMenu.getItemCount();

for(int j=0; j < numItems; ++j) {
nextItem = nextMenu.getItem(j);
System.out.println(nextItem);
}
System.out.println();
}
}
}

10.6.6 AWT兼容

 

10.7 菜单元素

 

10-15 实现定制菜单元素

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;
}
}

10.8 JPopupMenu

 

10-16 使用弹出式菜单

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
public void init() {
Container contentPane = getContentPane();
final JLabel label = new JLabel("Click here for popup");
final JPopupMenu popup = new JPopupMenu();
final JSlider slider = new JSlider();

popup.add(new JMenuItem("Copy", new ImageIcon(this.getClass().getResource("copy.gif"))));
popup.add(new CutAction(new ImageIcon(this.getClass().getResource("cut.gif"))));
popup.addSeparator();
popup.add(slider);

label.addMouseListener(new MouseAdapter() {
public void mousePressed (MouseEvent e) {
popup.show(label, e.getX(), e.getY());
}
});
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if( ! slider.getValueIsAdjusting())
popup.setVisible(false);
}
});

label.setHorizontalAlignment(JLabel.CENTER);
contentPane.add(label, BorderLayout.CENTER);
}
class CutAction extends AbstractAction {
java.net.URL iconurl;

public CutAction(Icon icon) {
//super("Cut", new ImageIcon("cut.gif"));
super("Cut",icon);
}
public void actionPerformed(ActionEvent e) {
System.out.println("cut");
}
}
}

10.8.1 弹出式菜单触发器

 

10-17 显示一个弹出式菜单以响应弹出式菜单触发器

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
private JPopupMenu popup = new JPopupMenu();

public void init() {
Container contentPane = getContentPane();

popup.add(new JMenuItem("item one"));
popup.add(new JMenuItem("item two"));
popup.add(new JMenuItem("item three"));
popup.add(new JMenuItem("item four"));

contentPane.addMouseListener(new MouseAdapter() {
public void mousePressed (MouseEvent e) {
showPopup(e);
}
public void mouseClicked (MouseEvent e) {
showPopup(e);
}
public void mouseReleased(MouseEvent e) {
showPopup(e);
}
});
}
void showPopup(MouseEvent e) {
if(e.isPopupTrigger())
popup.show(this, e.getX(), e.getY());
}
}

10.8.2 轻量/中量/重量弹出式菜单

 

10.8.3 弹出式菜单调用者

 

10-18 相对于其调用者显示弹出式菜单

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
JComboBox combobox = new JComboBox();
JPopupMenu popup = new JPopupMenu();
ColoredCanvas popupRelativeToMe;
ColoredCanvas blueCanvas, redCanvas, yellowCanvas;

public void init() {
Container contentPane = getContentPane();
blueCanvas = new ColoredCanvas(Color.blue);
redCanvas = new ColoredCanvas(Color.red);
yellowCanvas = new ColoredCanvas(Color.yellow);
popupRelativeToMe = blueCanvas;

popup.add(new JMenuItem("item one"));
popup.add(new JMenuItem("item two"));
popup.add(new JMenuItem("item three"));
popup.add(new JMenuItem("item four"));

contentPane.setLayout(new FlowLayout());
contentPane.add(new JLabel("Popup Over:"));
contentPane.add(combobox);
contentPane.add(blueCanvas);
contentPane.add(redCanvas);
contentPane.add(yellowCanvas);

combobox.addItem("Blue Canvas");
combobox.addItem("Yellow Canvas");
combobox.addItem("Red Canvas");

combobox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED) {
JComboBox c = (JComboBox)event.getSource();
String label = (String)c.getSelectedItem();

if(label.equals("Blue Canvas"))
popupRelativeToMe = blueCanvas;
else if(label.equals("Red Canvas"))
popupRelativeToMe = redCanvas;
else if(label.equals("Yellow Canvas"))
popupRelativeToMe = yellowCanvas;

popup.show(popupRelativeToMe, 5, 5);
}
}
});
}
}
class ColoredCanvas extends JPanel {
private Color color;

public ColoredCanvas(Color color) {
this.color = color;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);

Dimension size = getSize();
g.setColor (color);
g.fill3DRect(0,0,size.width-1,size.height-1,true);
}
public Dimension getPreferredSize() {
return new Dimension(100,100);
}
}

10.8.4 JPopupMenu属性

 

10.8.5 JPopupMenu事件

 

10-19 弹出式菜单事件的清单

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;

public class Test extends JApplet {
public void init() {
final Container contentPane = getContentPane();
final JPopupMenu popup = new JPopupMenu();

popup.add(new JMenuItem("item one"));
popup.add(new JMenuItem("item two"));
popup.add(new JMenuItem("item three"));
popup.add(new JMenuItem("item four"));

popup.addPopupMenuListener(new PopupMenuListener() {
public void popupMenuCanceled(PopupMenuEvent e) {
showStatus("menu canceled");
}
public void popupMenuWillBecomeVisible(
PopupMenuEvent e) {
showStatus("menu will become visible");
}
public void popupMenuWillBecomeInvisible(
PopupMenuEvent e) {
showStatus("menu will become invisible");
}
});
addMouseListener(new MouseAdapter() {
public void mousePressed (MouseEvent e) {
popup.show(contentPane, e.getX(), e.getY());
}
});
}
}

10.8.6 JPopupMenu类总结

 

10-20 为弹出式菜单设置位置、边框和调用者

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
private JPopupMenu popup = new JPopupMenu();

public void init() {
Container contentPane = getContentPane();
JLabel label = new JLabel("Click To Show Popup");

popup.add(new JMenuItem("item one"));
popup.add(new JMenuItem("item two"));
popup.add(new JMenuItem("item three"));
popup.add(new JMenuItem("item four"));

label.setHorizontalAlignment(JLabel.CENTER);
contentPane.add(label, BorderLayout.CENTER);

label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
//if(e.isPopupTrigger()) {
popup.setVisible(true);
//}
}
});
}
}

10.8.7 AWT兼容

 

10.9 JMenuBar

 

10-21 一个简单的菜单栏

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class Test extends JFrame {
public Test() {
final JMenuBar mb = new JMenuBar();
final JMenu fileMenu = new JMenu("File");
JMenuItem exitItem = new JMenuItem("Exit");

fileMenu.add("New ...");
fileMenu.add("Open ...");
fileMenu.add("Save");
fileMenu.add("Save As ..");
fileMenu.addSeparator();
fileMenu.add(exitItem);

mb.add(new JLabel(
new ImageIcon("smiley_face_small.gif")));

mb.add(fileMenu);

// Either one of the following two lines will
// attach the menu bar to the application
//setJMenuBar(mb);
getRootPane().setJMenuBar(mb);

exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
System.exit(0);
}
});
System.out.println("component count: " +
mb.getComponentCount());
System.out.println("first component: " +
(mb.getComponentAtIndex(0)).getClass().getName());

System.out.println("menu count: " + (mb.getMenuCount()));

JMenu menu = mb.getMenu(0);
if(menu == null) System.out.println("null menu");
else System.out.println("got menu");
}
public static void main(String args[]) {
GJApp.launch(new Test(),
"A Menu Bar",300,300,300,250);
}
}
class GJApp extends WindowAdapter {
static private JPanel statusArea = new JPanel();
static private JLabel status = new JLabel(" ");
static private ResourceBundle resources;

public static void launch(final JFrame f, String title,
final int x, final int y,
final int w, int h) {
launch(f,title,x,y,w,h,null);
}
public static void launch(final JFrame f, String title,
final int x, final int y,
final int w, int h,
String propertiesFilename) {
f.setTitle(title);
f.setBounds(x,y,w,h);
f.setVisible(true);

statusArea.setBorder(BorderFactory.createEtchedBorder());
statusArea.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
statusArea.add(status);
status.setHorizontalAlignment(JLabel.LEFT);

f.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);

if(propertiesFilename != null) {
resources = ResourceBundle.getBundle(
propertiesFilename, Locale.getDefault());
}

f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
static public JPanel getStatusArea() {
return statusArea;
}
static public void showStatus(String s) {
status.setText(s);
}
static Object getResource(String key) {
if(resources != null) {
return resources.getString(key);
}
return null;
}
}

10.9.1 菜单栏菜单和组件

 

10-22 菜单栏中的菜单和组件

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
public void init() {
Container contentPane = getContentPane();

final JMenuBar mb = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenuItem exitItem = new JMenuItem("Exit");
JButton compButton = new JButton(
"show menubar components ...");
JButton menuButton = new JButton(
"show menubar menus ...");

fileMenu.add("New ...");
fileMenu.add("Open ...");
fileMenu.add("Save");
fileMenu.add("Save As ..");
fileMenu.addSeparator();
fileMenu.add(exitItem);

editMenu.add("Undo");
editMenu.addSeparator();
editMenu.add("Cut");
editMenu.add("Copy");
editMenu.add("Paste");

mb.setMargin(new Insets(30,20,10,5));
mb.add(new JLabel(new ImageIcon("smiley.gif")));
mb.add(fileMenu);
mb.add(editMenu);

setJMenuBar(mb);
contentPane.setLayout(new FlowLayout());
contentPane.add(compButton);
contentPane.add(menuButton);

exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component c;
int cnt = mb.getMenuCount();

for(int i=0; i < cnt; ++i) {
c = mb.getMenu(i);
System.out.println(c);
System.out.println();
}
}
});
compButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component c;
int cnt = mb.getComponentCount();

for(int i=0; i < cnt; ++i) {
c = mb.getComponentAtIndex(i);
System.out.println(c);
System.out.println();
}
}
});
}
}

10.9.2 JMenuBar属性

 

10.9.3 JMenuBar事件

 

10.9.4JMenuBar类总结

 

10.9.5 AWT兼容

 

10.10 JToolBar

 

10-23 把组件添加到一个菜单栏中

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test extends JApplet {
public Test() {
Container contentPane = getContentPane();
JToolBar tb = new JToolBar();
JComboBox fontCombo = new JComboBox(),
fontSizeCombo = new JComboBox();

JButton newButton = new JButton(new ImageIcon("new.gif")),
openButton = new JButton(new ImageIcon("open.gif")),
cutButton = new JButton(new ImageIcon("cut.gif")),
copyButton = new JButton(new ImageIcon("copy.gif")),
pasteButton = new JButton(new ImageIcon("paste.gif"));

fontCombo.addItem("Helvetica");
fontCombo.addItem("Palatino");
fontCombo.addItem("Courier");
fontCombo.addItem("Times");
fontCombo.addItem("Times-Roman");

fontSizeCombo.addItem("10");
fontSizeCombo.addItem("12");
fontSizeCombo.addItem("14");
fontSizeCombo.addItem("16");
fontSizeCombo.addItem("18");

tb.add(newButton);
tb.add(openButton);

tb.addSeparator();

tb.add(cutButton);
tb.add(copyButton);
tb.add(pasteButton);

tb.addSeparator();

tb.add(fontCombo);
tb.add(fontSizeCombo);

contentPane.setLayout(new BorderLayout());
contentPane.add(tb, BorderLayout.NORTH);
}
}

10-24 把组件添加到一个工具条中(方法2)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test extends JApplet {
public Test() {
Container contentPane = getContentPane();
JToolBar tb = new JToolBar();
JComboBox fontCombo = new JComboBox(),
fontSizeCombo = new JComboBox();

JButton newButton = new JButton(new ImageIcon("new.gif")),
openButton = new JButton(new ImageIcon("open.gif")),
cutButton = new JButton(new ImageIcon("cut.gif")),
copyButton = new JButton(new ImageIcon("copy.gif")),
pasteButton = new JButton(new ImageIcon("paste.gif"));

fontCombo.addItem("Helvetica");
fontCombo.addItem("Palatino");
fontCombo.addItem("Courier");
fontCombo.addItem("Times");
fontCombo.addItem("Times-Roman");

fontSizeCombo.addItem("10");
fontSizeCombo.addItem("12");
fontSizeCombo.addItem("14");
fontSizeCombo.addItem("16");
fontSizeCombo.addItem("18");

tb.add(newButton);
tb.add(openButton);

tb.addSeparator();

tb.add(cutButton);
tb.add(copyButton);
tb.add(pasteButton);

tb.addSeparator();

tb.add(fontCombo);
tb.add(fontSizeCombo);

newButton.setAlignmentY(0.5f);
openButton.setAlignmentY(0.5f);
cutButton.setAlignmentY(0.5f);
copyButton.setAlignmentY(0.5f);
pasteButton.setAlignmentY(0.5f);

newButton.setAlignmentX(0.5f);
openButton.setAlignmentX(0.5f);
cutButton.setAlignmentX(0.5f);
copyButton.setAlignmentX(0.5f);
pasteButton.setAlignmentX(0.5f);

fontCombo.setMaximumSize(fontCombo.getPreferredSize());
fontSizeCombo.setMaximumSize(
fontSizeCombo.getPreferredSize());

contentPane.setLayout(new BorderLayout());
contentPane.add(tb, BorderLayout.NORTH);
}
}

 

10.10.1 滚过式工具条

 

10-25 JTooBar.isRollover属性

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
public void init() {
Container contentPane = getContentPane();
JToolBar toolbar = new JToolBar();

toolbar.add(new NewAction());
toolbar.add(new OpenAction());
toolbar.addSeparator();
toolbar.add(new CutAction());
toolbar.add(new CopyAction());
toolbar.add(new PasteAction());

toolbar.putClientProperty("JToolBar.isRollover",
Boolean.TRUE);

contentPane.add(toolbar, BorderLayout.NORTH);
}
class NewAction extends AbstractAction {
public NewAction() {
putValue(Action.SMALL_ICON,
new ImageIcon("new.gif"));
}
public void actionPerformed(ActionEvent event) {
showStatus("new");
}
}
class OpenAction extends AbstractAction {
public OpenAction() {
putValue(Action.SMALL_ICON,
new ImageIcon("open.gif"));
}
public void actionPerformed(ActionEvent event) {
showStatus("open");
}
}
class CutAction extends AbstractAction {
public CutAction() {
putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
}
public void actionPerformed(ActionEvent event) {
showStatus("cut");
}
}
class CopyAction extends AbstractAction {
public CopyAction() {
putValue(Action.SMALL_ICON,
new ImageIcon("copy.gif"));
}
public void actionPerformed(ActionEvent event) {
showStatus("copy");
}
}
class PasteAction extends AbstractAction {
public PasteAction() {
putValue(Action.SMALL_ICON,
new ImageIcon("paste.gif"));
}
public void actionPerformed(ActionEvent event) {
showStatus("paste");
}
}
}

10.10.2 在工具条中使用动作

 

10-26 把动作添加到一个工具条中

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet {
public void init() {
Container contentPane = getContentPane();
JToolBar toolbar = new JToolBar();

toolbar.add(new NewAction());
toolbar.add(new OpenAction());
toolbar.addSeparator();
toolbar.add(new CutAction());
toolbar.add(new CopyAction());
toolbar.add(new PasteAction());

contentPane.add(toolbar, BorderLayout.NORTH);
}
class NewAction extends AbstractAction {
public NewAction() {
super("new", new ImageIcon("new.gif"));
}
public void actionPerformed(ActionEvent event) {
showStatus("new");
}
}
class OpenAction extends AbstractAction {
public OpenAction() {
putValue(Action.SMALL_ICON,
new ImageIcon("open.gif"));
}
public void actionPerformed(ActionEvent event) {
showStatus("open");
}
}
class CutAction extends AbstractAction {
public CutAction() {
super("cut", new ImageIcon("cut.gif"));
putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
}
public void actionPerformed(ActionEvent event) {
showStatus("cut");
}
}
class CopyAction extends AbstractAction {
public CopyAction() {
putValue(Action.SMALL_ICON,
new ImageIcon("copy.gif"));
}
public void actionPerformed(ActionEvent event) {
showStatus("copy");
}
}
class PasteAction extends AbstractAction {
public PasteAction() {
putValue(Action.SMALL_ICON,
new ImageIcon("paste.gif"));
}
public void actionPerformed(ActionEvent event) {
showStatus("paste");
}
}
}

10.10.3 浮动工具条

 

10-27 固定位置的工具提示

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test extends JApplet {
public Test() {
Container contentPane = getContentPane();
JToolBar toolbar = new JToolBar();

String[] tooltipTexts = { "new", "open", "cut", "copy",
"paste"
};

ImageIcon[] icons = {
new ImageIcon("new.gif"),
new ImageIcon("open.gif"),
new ImageIcon("cut.gif"),
new ImageIcon("copy.gif"),
new ImageIcon("paste.gif")
};

JButton[] buttons = {
new ButtonWithFixedTooltip(icons[0],tooltipTexts[0]),
new ButtonWithFixedTooltip(icons[1],tooltipTexts[1]),
new ButtonWithFixedTooltip(icons[2],tooltipTexts[2]),
new ButtonWithFixedTooltip(icons[3],tooltipTexts[3]),
new ButtonWithFixedTooltip(icons[4],tooltipTexts[4])
};

for(int i=0; i < buttons.length; ++i) {
toolbar.add(buttons[i]);

if(tooltipTexts[i].equals("open"))
toolbar.addSeparator();
}
contentPane.add(toolbar, BorderLayout.NORTH);
}
}
class ButtonWithFixedTooltip extends JButton {
public ButtonWithFixedTooltip(Icon icon, String tooltipText) {
super(icon);
setToolTipText(tooltipText);
}
public Point getToolTipLocation(MouseEvent e){
Dimension size = getSize();
return new Point(0, size.height);
}
}

10.10.4 位置固定的工具提示

 

10.10.5 JToolBar属性

 

10.10.6 JMenuBar事件

 

10.10.7 JMenuBar类总结

 

10.10.8 AWT兼容

 

10.11 本章回顾

 

上一篇:第12章 轻量容器(续)


下一篇:第17章 列表