📄 menuexample12.java
字号:
package JFCBook.Chapter6.jdk13;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import JFCBook.Chapter6.FileManager;
public class MenuExample12 extends JFrame {
public MenuExample12(String title) {
super(title);
this.getContentPane().add(
new JScrollPane(textArea = new JTextArea(20, 40)),
BorderLayout.CENTER);
fileManager = new FileManager();
AbstractAction exitAction = new AbstractAction() {
{
putValue(NAME, "Exit");
putValue(MNEMONIC_KEY, new Integer('X'));
putValue(SHORT_DESCRIPTION, "Closes the open file and exits the application");
putValue(LONG_DESCRIPTION, "Closing the application");
}
public void actionPerformed(ActionEvent evt) {
closeWindow();
}
};
// Action for the "Enable writing menu item"
final AbstractAction enableWritingAction = new AbstractAction() {
{ // Constructor
putValue(NAME, "Enable writing");
putValue(MNEMONIC_KEY, new Integer('W'));
putValue(SHORT_DESCRIPTION,
"Allows writing to the next file to be opened");
putValue(LONG_DESCRIPTION, "Enabling writing to file");
}
public void actionPerformed(ActionEvent evt) {
// Nothing to do
}
};
// Processing for "Save..." menu item
final AbstractAction saveAction = new AbstractAction() {
{ // Constructor
putValue(NAME, "Save...");
putValue(SMALL_ICON, saveIcon);
putValue(MNEMONIC_KEY, new Integer('S'));
putValue(SHORT_DESCRIPTION, "Saves the currently open file");
putValue(LONG_DESCRIPTION, "Saving...");
setEnabled(false);
}
public void actionPerformed(ActionEvent evt) {
try {
fileManager.saveFile(textArea.getText());
} catch (IOException e) {
// Do nothing - message already printed
}
}
};
// Processing for "Save As..." menu item
final AbstractAction saveAsAction = new AbstractAction() {
{ // Constructor
putValue(NAME, "Save As...");
putValue(MNEMONIC_KEY, new Integer('A'));
putValue(SHORT_DESCRIPTION, "Saves the open file under a new name");
putValue(LONG_DESCRIPTION, "Saving...");
setEnabled(false);
}
public void actionPerformed(ActionEvent evt) {
if (fileManager.isFileOpen()) {
String name = getFileName("Save As File", FileDialog.SAVE);
if (name != null) {
try {
fileManager.saveAsFile(name, textArea.getText());
} catch (IOException e) {
// Do nothing - message already printed
}
}
}
}
};
// Action for "New..." menu item
AbstractAction newAction = new AbstractAction() {
{ // Constructor
putValue(NAME, "New...");
putValue(SMALL_ICON, newIcon);
putValue(MNEMONIC_KEY, new Integer('N'));
putValue(SHORT_DESCRIPTION, "Creates a new file");
putValue(LONG_DESCRIPTION, "Creating new file...");
}
public void actionPerformed(ActionEvent evt) {
String name = getFileName("New File", FileDialog.SAVE);
if (name != null) {
if (fileManager.isFileOpen()) {
// Close any open file
try {
fileManager.closeFile(textArea.getText());
} catch (Throwable e) {
// Ignore any exception
}
}
try {
fileManager.newFile(name);
textArea.setText("");
textArea.setEditable(true); // Always writable
writeItem.setState(true); // Check writable box
fileManager.setWritable(true); // Allow writes to file
addRecentFile(name);
// Enable saving
saveAction.setEnabled(true);
} catch (IOException e) {
// Do nothing - message already printed
}
}
}
};
// Processing for "Open..." menu item
AbstractAction openAction = new AbstractAction() {
{ // Constructor
putValue(NAME, "Open...");
putValue(SMALL_ICON, openIcon);
putValue(MNEMONIC_KEY, new Integer('O'));
putValue(SHORT_DESCRIPTION, "Opens an existing file");
putValue(LONG_DESCRIPTION, "Opening file...");
}
public void actionPerformed(ActionEvent evt) {
String name = getFileName("Open File", FileDialog.LOAD);
if (name != null) {
try {
String text = fileManager.openFile(name);
textArea.setText(text);
// Enable for writing if allowed to
boolean canWrite = fileManager.canWrite() &&
writeItem.getState();
textArea.setEditable(canWrite);
fileManager.setWritable(writeItem.getState());
addRecentFile(name);
// Enable saving if writable
saveAction.setEnabled(canWrite);
} catch (IOException e) {
// Do nothing - message already printed
}
}
}
};
// Processing for "Close..." menu item
final AbstractAction closeAction = new AbstractAction() {
{ // Constructor
putValue(NAME, "Close");
putValue(MNEMONIC_KEY, new Integer('C'));
putValue(SHORT_DESCRIPTION, "Closes the currently open file");
putValue(LONG_DESCRIPTION, "Closing file...");
setEnabled(false);
}
public void actionPerformed(ActionEvent evt) {
try {
fileManager.closeFile(textArea.getText());
textArea.setText("");
// Disable saving
saveAction.setEnabled(false);
} catch (IOException e) {
// Do nothing - message already printed
}
}
};
// The handler for the recent file list
menuAction = new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
String fileName = evt.getActionCommand();
try {
String text = fileManager.openFile(fileName);
textArea.setText(text);
addRecentFile(fileName);
// Enable for writing if allowed to
boolean canWrite = fileManager.canWrite() &&
writeItem.getState();
textArea.setEditable(canWrite);
fileManager.setWritable(writeItem.getState());
} catch (IOException e) {
// Do nothing - message already printed
}
}
};
// Create the menu system using the Actions
JMenuBar mb = new JMenuBar();
this.setJMenuBar(mb);
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
mb.add(fileMenu);
JMenuItem newItem = new JMenuItem(newAction);
JMenuItem openItem = new JMenuItem(openAction);
JMenuItem closeItem = new JMenuItem(closeAction);
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(closeItem);
fileMenu.addSeparator();
writeItem = new JCheckBoxMenuItem();
writeItem.setState(true);
writeItem.setAction(enableWritingAction);
fileMenu.add(writeItem);
fileMenu.addSeparator();
JMenuItem saveItem = new JMenuItem(saveAction);
JMenuItem saveAsItem = new JMenuItem(saveAsAction);
fileMenu.add(saveItem);
fileMenu.add(saveAsItem);
fileMenu.addSeparator();
fileListMenu = new JMenu("Recent Files");
fileListMenu.setMnemonic('R');
fileMenu.add(fileListMenu);
JMenuItem emptyListItem = new JMenuItem("Empty");
emptyListItem.setEnabled(false);
fileListMenu.add(emptyListItem);
fileMenu.addSeparator();
JMenuItem exitItem = new JMenuItem(exitAction);
fileMenu.add(exitItem);
// Create and add the toolbar
JToolBar toolBar = new JToolBar();
toolBar.add(newAction);
toolBar.add(openAction);
toolBar.add(saveAction);
this.getContentPane().add(toolBar, BorderLayout.NORTH);
// Processing for the "File" menu
fileMenu.addMenuListener(new MenuListener() {
public void menuSelected(MenuEvent evt) {
boolean fileOpen = fileManager.isFileOpen();
// Allow close only if we have an open file
closeAction.setEnabled(fileOpen);
// Similarly, allow "Enable write" only if no open file
enableWritingAction.setEnabled(fileOpen == false);
// If we have an open file, enable Save and Save As
// if the user has selected Enable Write AND the
// file can be written to.
boolean canSave = (fileOpen && writeItem.getState() &&
fileManager.canWrite());
saveAction.setEnabled(canSave);
saveAsAction.setEnabled(canSave);
}
public void menuDeselected(MenuEvent evt) {
// Not used
}
public void menuCanceled(MenuEvent evt) {
// Not used
}
});
// Add accelerators
newItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK, false));
openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK, false));
exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK, false));
// Create the ButtonSnooper and connect it to the menus
ButtonSnooper snooper = new ButtonSnooper();
snooper.attachToMenuBar(mb);
// Connect the snooper to the buttons in the toolbar
snooper.attachToButtons(toolBar);
// Create and add a status line connected to the snooper
this.getContentPane().add(new StatusLine(snooper), BorderLayout.SOUTH);
}
// Add a name to the recent file list
public void addRecentFile(String fileName) {
int offset;
// Check whether this file is already in the file list
if ((offset = recentFiles.indexOf(fileName)) == -1) {
// Not present - add it at the beginning
recentFiles.insertElementAt(fileName, 0);
if (recentFiles.size() > RECENT_FILES) {
// List was full - remove the last (oldest) item
recentFiles.removeElementAt(RECENT_FILES);
}
} else {
// Already present: move this item to the front of the list
recentFiles.removeElementAt(offset);
recentFiles.insertElementAt(fileName, 0);
}
// Rebuild the file menu
buildRecentFileMenu();
}
// Build the recent file menu
public void buildRecentFileMenu() {
int size = recentFiles.size();
fileListMenu.removeAll();
for (int i = 1; i <= size; i++) {
String fileName = (String)(recentFiles.elementAt(i - 1));
JMenuItem mi = new JMenuItem();
mi.setAction(menuAction);
mi.setActionCommand(fileName);
mi.setText(i + " " + fileName);
mi.setMnemonic('0' + i);
fileListMenu.add(mi);
}
}
// Get a file name
public String getFileName(String title, int mode) {
FileDialog fd = new FileDialog(this, title, mode);
fd.setFile("*.*");
fd.setDirectory(directory);
fd.setVisible(true);
String dir = fd.getDirectory();
String file = fd.getFile();
if (dir == null || file == null) {
return null;
}
directory = dir;
String separator = System.getProperty("file.separator");
if (dir.endsWith(separator)) {
return dir + file;
} else {
return dir + System.getProperty("file.separator") + file;
}
}
// Take any action needed to close the application
public void closeWindow() {
try {
fileManager.closeFile(textArea.getText());
} catch (IOException e) {
System.out.println("Failed to write data on close.");
}
System.exit(0);
}
public static void main(String[] args) {
JFrame f = new MenuExample12("Menu Example 11");
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
MenuExample12 frame = (MenuExample12)(evt.getSource());
frame.closeWindow();
}
});
}
JCheckBoxMenuItem writeItem;
JMenu fileListMenu;
JTextArea textArea;
FileManager fileManager;
String directory = ""; // Current directory
Action menuAction;
// Recently-used file list
static final int RECENT_FILES = 4;
Vector recentFiles = new Vector(RECENT_FILES);
// Icons
static Class thisClass = MenuExample12.class;
static Icon newIcon = new ImageIcon(thisClass.getResource("images/new.gif"));
static Icon openIcon = new ImageIcon(thisClass.getResource("images/open.gif"));
static Icon saveIcon = new ImageIcon(thisClass.getResource("images/save.gif"));
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -