Java Swing phần 9 ppsx

99 357 0
Java Swing phần 9 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Java Swing - O’Reilly - 793 - Hashtable, so that we can access any action we need by name. In this example, we then retrieve the "cut" action from the table using the DefaultEditorKit.cutAction constant: [1] The keen observer will notice that the properties table indicated that there were 47 actions available. One action is not defined as a constant, but is still available by the name "dump-model." This action just calls dump() on the document of the currently focused JTextComponent (assuming it's an AbstractDocument), causing the model structure to be printed to System.err. Hashtable actionHash = new Hashtable(); Action[] actions = edKit.getActions(); for (int i=0; i<actions.length; i++) { String name = (String)actions[i].getValue(Action.NAME); actionHash.put(name, actions[i]); } Action cut = (Action)actionHash.get(DefaultEditorKit.cutAction); Table 24.3, DefaultEditorKit Action Name Constants Constant Description backwardAction Move the caret back one position beepAction Create a beep (Toolkit.beep()) beginAction Move the caret to the beginning of the document beginLineAction Move the caret to the beginning of the current line beginParagraphAction Move the caret to the beginning of the current paragraph beginWordAction Move the caret to the beginning of the current word copyAction Copy the selected region and place it on the system clipboard cutAction Cut the selected region and place it on the system clipboard defaultKeyTypedAction Display the pressed key (default when there is no special keymap entry for a pressed key) deleteNextCharAction Delete the character following the caret position deletePrevCharAction Delete the character before the caret position downAction Move the caret down one position endAction Move the caret to the end of the document endLineAction Move the caret to the end of the current line endParagraphAction Move the caret to the end of the current paragraph endWordAction Move the caret to the end of the current word forwardAction Move the caret forward one position insertBreakAction Insert a line or paragraph break (\n) into the document; if there is a current selection, it is removed first insertContentAction Insert content into the document; if there is a current selection, it is removed first insertTabAction Insert a tab character into the document; if there is a current selection, it is removed first nextWordAction Move the caret to the beginning of the next word pageDownAction Page the document down pageUpAction Page the document up pasteAction Paste the contents of the system clipboard at the caret position; if there is a current selection, it is replaced by the pasted content previousWordAction Move the caret to the beginning of the previous word readOnlyAction Set the editor to read-only mode; results in a call to setEditable(false) on the JTextComponent selectAllAction Highlight the entire document selectLineAction Select the current line selectParagraphAction Select the current paragraph selectWordAction Select the current word Java Swing - O’Reilly - 794 - selectionBackwardAction Adjust the current selection by moving the caret back one position selectionBeginAction Adjust the current selection by moving the caret back to the beginning of the document selectionBeginLineAction Adjust the current selection by moving the caret back to the beginning of the current line selectionBeginParagraphAction Adjust the current selection by moving the caret back to the beginning of the current paragraph selectionBeginWordAction Adjust the current selection by moving the caret back to the beginning of the current word selectionDownAction Adjust the current selection by moving the caret down one row selectionEndAction Adjust the current selection by moving the caret to the end of the document selectionEndLineAction Adjust the current selection by moving the caret to the end of the current line selectionEndParagraphAction Adjust the current selection by moving the caret to the end of the current paragraph selectionEndWordAction Adjust the current selection by moving the caret to the end of the current word selectionForwardAction Adjust the current selection by moving the caret forward one position selectionNextWordAction Adjust the current selection by moving the caret to the beginning of the next word selectionPreviousWordAction Adjust the current selection by moving the caret to the beginning of the previous word selectionUpAction Adjust the current selection by moving the caret down one row upAction Move the caret up one position writableAction Set the editor to writable mode; results in a call to setEditable(true) on the JTextComponent 24.1.3.3 Using Actions Let's look at a simple example that shows how these actions can be used. In this program, we'll create a JTextArea and add all the available actions to a menu (the list is pretty long, so we split it into two submenus). As we discussed in the chapter on menus, we can add these Action objects directly to the menu. The default action names appear as menu selections. Since JTextArea gets its actions from the DefaultEditorKit, you'll see each of the actions listed in Table 24.3 when you run this program. By blindly adding all of the actions, we avoid interacting with the editor kit directly in this program. At the end of this section, we'll look at a much more useful example that uses DefaultEditorKit directly. // TextActionExample.java // import javax.swing.*; import javax.swing.text.*; // Simple TextAction example public class TextActionExample { public static void main(String[] args) { Java Swing - O’Reilly - 795 - // Create a text area JTextArea ta = new JTextArea(); ta.setLineWrap(true); // Add all actions to the menu (split into two menus to make it more usable) Action[] actions = ta.getActions(); JMenuBar menubar = new JMenuBar(); JMenu actionmenu = new JMenu("Actions"); menubar.add(actionmenu); JMenu firstHalf = new JMenu("1st Half"); JMenu secondHalf = new JMenu("2nd Half"); actionmenu.add(firstHalf); actionmenu.add(secondHalf); int mid = actions.length/2; for (int i=0; i<mid; i++) { firstHalf.add(actions[i]); } for (int i=mid; i<actions.length; i++) { secondHalf.add(actions[i]); } // Show it . . . JFrame f = new JFrame(); f.addWindowListener(new BasicWindowMonitor()); f.getContentPane().add(ta); f.setJMenuBar(menubar); f.setSize(300, 200); f.setVisible(true); } } That's all there is to it! All we did was call getActions() on the JTextArea (which ultimately retrieved the actions from a DefaultEditorKit) and added each action to the menu. Of course, most of these actions would never be provided as menu options, and for those that would, you'd probably want to change the label (the default labels are all lowercase and the words are hyphen- separated; e.g., cut-to-clipboard). The example at the end of the section is a bit more realistic and will address these issues. 24.1.3.4 Constructor public DefaultEditorKit() This default constructor defines no behavior. 24.1.3.5 Methods The following methods provide default implementations for all of the abstract methods defined in EditorKit. public Object clone() Returns a new DefaultEditorKit. public Caret createCaret() Java Swing - O’Reilly - 796 - Returns null. See EditorKit.createCaret(). public Document createDefaultDocument() Creates a new PlainDocument instance and returns it. public void read(InputStream in, Document doc, int pos)throws IOException, BadLocationException public void read(Reader in, Document doc, int pos)throws IOException, BadLocationException Read plain text from the given Reader (in), adding the text at the specified position. The version that takes an InputStream simply wraps the stream in an InputStreamReader and calls the other version. public void write(OutputStream out, Document doc, int pos, int len)throws IOException, BadLocationException public void write(Writer out, Document doc, int pos, int len)throws IOException, BadLocationException Write len plain text characters to the given Writer (out), starting at position pos. The version that takes an OutputStream simply wraps the stream in an OutputStreamWriter and calls the other version. 24.1.4 The DefaultEditorKit.DefaultKeyTypedAction Class Over the next few pages, we'll give a brief overview of the actions defined as public static inner classes of DefaultEditorKit. The first of these is the default action, used to insert text into the active JTextComponent. 24.1.4.1 Constructor public DefaultKeyTypedAction() Creates an action using the name defaultKeyTypedAction. 24.1.4.2 Method public void actionPerformed(ActionEvent e) Inserts the actionCommand value from the given event into the active JTextComponent using replaceSelection(). If the first character has a value less than 0x20, this does nothing. 24.1.5 The DefaultEditorKit.BeepAction Class 24.1.5.1 Constructor public BeepAction() Creates an action using the name beepAction. Java Swing - O’Reilly - 797 - 24.1.5.2 Method public void actionPerformed(ActionEvent e) Calls Toolkit.getDefaultToolkit().beep(). 24.1.6 The DefaultEditorKit.CopyAction Class 24.1.6.1 Constructor public CopyAction() Creates an action using the name copyAction. 24.1.6.2 Method public void actionPerformed(ActionEvent e) Calls copy() on the active JTextComponent, if it can be determined. 24.1.7 The DefaultEditorKit.CutAction Class 24.1.7.1 Constructor public CutAction() Creates an action using the name cutAction. 24.1.7.2 Method public void actionPerformed(ActionEvent e) Calls cut() on the active JTextComponent, if it can be determined. 24.1.8 The DefaultEditorKit.InsertBreakAction Class 24.1.8.1 Constructor public InsertBreakAction() Creates an action using the name insertBreakAction. 24.1.8.2 Method public void actionPerformed(ActionEvent e) Replaces the current selection with a \n (return) character, if an active JTextComponent can be determined. If there is no selection, a \n is inserted. 24.1.9 The DefaultEditorKit.InsertContentAction Class 24.1.9.1 Constructor Java Swing - O’Reilly - 798 - public InsertContentAction() Creates an action using the name insertContentAction. 24.1.9.2 Method public void actionPerformed(ActionEvent e) Inserts the actionCommand value from the given event into the active JTextComponent, using replaceSelection(). If the action command is null, a beep is sounded. 24.1.10 The DefaultEditorKit.InsertTabAction Class 24.1.10.1 Constructor public InsertTabAction() Creates an action using the name insertTabAction. 24.1.10.2 Method public void actionPerformed(ActionEvent e) Replaces the current selection with a \t (tab) character, if an active JTextComponent can be determined. If there is no selection, a tab is inserted. 24.1.11 The DefaultEditorKit.PasteAction Class 24.1.11.1 Constructor public PasteAction() Creates an action using the name pasteAction. 24.1.11.2 Method public void actionPerformed(ActionEvent e) Calls paste() on the active JTextComponent, if it can be determined. 24.1.12 A Simple Text Editor In this first example, we'll show how to do some of things you'd expect from a basic editor. Our first editor will support the following features: • Cut, copy, and paste via toolbar buttons, menu selection, and default key shortcuts • Select-all capability via menu selection • Quick keyboard navigation using the nextWordAction, previousWordAction, selectionNextWordAction, and selectionPreviousWordAction • Saving and loading documents When we run it, our simple editor will look something like Figure 24.3. [2] Java Swing - O’Reilly - 799 - [2] Text in this and following figures is from A.M. Turing, "Computing Machinery and Intelligence," Mind, 1950. Figure 24.3. SimpleEditor Here's the source code for SimpleEditor. It's designed to be easily extensible, allowing us to add features of the more advanced editor kits. This class serves as the base class for the other examples in this chapter. // SimpleEditor.java // import javax.swing.*; import javax.swing.text.*; import java.awt.*; import java.io.*; import java.awt.event.*; import java.util.Hashtable; // An example showing several DefaultEditorKit features. This class is designed // to be easily extended to add additional functionality. public class SimpleEditor extends JFrame { public static void main(String[] args) { SimpleEditor editor = new SimpleEditor(); editor.addWindowListener(new BasicWindowMonitor()); editor.setVisible(true); } // Create an editor public SimpleEditor() { super("Swing Editor"); textComp = createTextComponent(); hashDefaultActions(); makeActionsPretty(); updateKeymap(); Container content = getContentPane(); content.add(textComp, BorderLayout.CENTER); content.add(createToolBar(), BorderLayout.NORTH); setJMenuBar(createMenuBar()); setSize(320, 240); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent ev) { System.exit(0); } }); } // Create the JTextComponent subclass. protected JTextComponent createTextComponent() { Java Swing - O’Reilly - 800 - JTextArea ta = new JTextArea(); ta.setLineWrap(true); return ta; } // Get all of the actions defined for our text component. Hash each one by name // so we can look for it later. protected void hashDefaultActions() { Action[] actions = textComp.getActions(); for (int i=0; i<actions.length; i++) { String name = (String)actions[i].getValue(Action.NAME); actionHash.put(name, actions[i]); } } // Get an action by name protected Action getHashedAction(String name) { return (Action)actionHash.get(name); } // Add icons and friendly names to actions we care about protected void makeActionsPretty() { Action a; a = getHashedAction(DefaultEditorKit.cutAction); a.putValue(Action.SMALL_ICON, new ImageIcon("icons/cut.gif")); a.putValue(Action.NAME, "Cut"); a = getHashedAction(DefaultEditorKit.copyAction); a.putValue(Action.SMALL_ICON, new ImageIcon("icons/copy.gif")); a.putValue(Action.NAME, "Copy"); a = getHashedAction(DefaultEditorKit.pasteAction); a.putValue(Action.SMALL_ICON, new ImageIcon("icons/paste.gif")); a.putValue(Action.NAME, "Paste"); a = getHashedAction(DefaultEditorKit.selectAllAction); a.putValue(Action.NAME, "Select All"); } // Add some key->Action mappings protected void updateKeymap() { // Create a new child Keymap Keymap map = JTextComponent.addKeymap("NextPrevMap", textComp.getKeymap()); // Define the keystrokes to be added KeyStroke next = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.CTRL_MASK, false); KeyStroke prev = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.CTRL_MASK, false); KeyStroke selNext = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.CTRL_MASK|InputEvent.SHIFT_MASK, false); KeyStroke selPrev = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.CTRL_MASK|InputEvent.SHIFT_MASK, false); // Add the new mappings used DefaultEditorKit actions map.addActionForKeyStroke(next, getHashedAction( DefaultEditorKit.nextWordAction)); map.addActionForKeyStroke(prev, getHashedAction( DefaultEditorKit.previousWordAction)); map.addActionForKeyStroke(selNext, getHashedAction( DefaultEditorKit.selectionNextWordAction)); Java Swing - O’Reilly - 801 - map.addActionForKeyStroke(selPrev, getHashedAction( DefaultEditorKit.selectionPreviousWordAction)); // Set the Keymap for the text component textComp.setKeymap(map); } // Create a simple JToolBar with some buttons protected JToolBar createToolBar() { JToolBar bar = new JToolBar(); // Add simple actions for opening & saving bar.add(getOpenAction()).setText(""); bar.add(getSaveAction()).setText(""); bar.addSeparator(); // Add cut/copy/paste buttons bar.add(getHashedAction(DefaultEditorKit.cutAction)).setText(""); bar.add(getHashedAction(DefaultEditorKit.copyAction)).setText(""); bar.add(getHashedAction(DefaultEditorKit.pasteAction)).setText(""); return bar; } // Create a JMenuBar with file & edit menus protected JMenuBar createMenuBar() { JMenuBar menubar = new JMenuBar(); JMenu file = new JMenu("File"); JMenu edit = new JMenu("Edit"); menubar.add(file); menubar.add(edit); file.add(getOpenAction()); file.add(getSaveAction()); file.add(new ExitAction()); edit.add(getHashedAction(DefaultEditorKit.cutAction)); edit.add(getHashedAction(DefaultEditorKit.copyAction)); edit.add(getHashedAction(DefaultEditorKit.pasteAction)); edit.add(getHashedAction(DefaultEditorKit.selectAllAction)); return menubar; } // Subclass can override to use a different open action protected Action getOpenAction() { return openAction; } // Subclass can override to use a different save action protected Action getSaveAction() { return saveAction; } protected JTextComponent getTextComponent() { return textComp; } private Action openAction = new OpenAction(); private Action saveAction = new SaveAction(); private JTextComponent textComp; private Hashtable actionHash = new Hashtable(); // ********** ACTION INNER CLASSES ********** // // A very simple "exit" action public class ExitAction extends AbstractAction { public ExitAction() { super("Exit"); } public void actionPerformed(ActionEvent ev) { System.exit(0); } } // An action that opens an existing file Java Swing - O’Reilly - 802 - class OpenAction extends AbstractAction { public OpenAction() { super("Open", new ImageIcon("icons/open.gif")); } // Query user for a filename and attempt to open and read the file into the // text component public void actionPerformed(ActionEvent ev) { String filename = JOptionPane.showInputDialog( SimpleEditor.this, "Enter Filename"); if (filename == null) return; FileReader reader = null; try { reader = new FileReader(filename); textComp.read(reader, null); } catch (IOException ex) { JOptionPane.showMessageDialog(SimpleEditor.this, "File Not Found", "ERROR", JOptionPane.ERROR_MESSAGE); } finally { if (reader != null) { try { reader.close(); } catch (IOException x) {} } } } } // An action that saves the document to a file class SaveAction extends AbstractAction { public SaveAction() { super("Save", new ImageIcon("icons/save.gif")); } // Query user for a filename and attempt to open and write the text // component's content to the file public void actionPerformed(ActionEvent ev) { String filename = JOptionPane.showInputDialog( SimpleEditor.this, "Enter Filename"); if (filename == null) return; FileWriter writer = null; try { writer = new FileWriter(filename); textComp.write(writer); } catch (IOException ex) { JOptionPane.showMessageDialog(SimpleEditor.this, "File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE); } finally { if (writer != null) { try { writer.close(); } catch (IOException x) {} } } } [...]... done is provided new implementations of the getSaveAction() and getOpenAction() methods and defined the new actions returned by these methods // IOStyledEditor .java // import import import import javax .swing. *; javax .swing. text.*; java. awt.event.*; java. io.*; // An extension of StyledEditor that adds document serialization public class IOStyledEditor extends StyledEditor { public static void main(String[]... decrIndent() - 821 - Java Swing - O’Reilly Decrements the indent level 24.1.26.6 Implementing AbstractWriter Here's a simple AbstractWriter subclass that shows how you might write out a document In this example, we just write out the name and attributes of each element If the element is a leaf, we write out its text // SimpleWriter .java // import javax .swing. text.*; import java. io.*; import java. awt.*; public... CTRL-U to change the font style (taking advantage of the CtrlIFocusManager class we wrote in Chapter 22) Here's the code for our new and improved editor: // StyledEditor .java // import javax .swing. *; import javax .swing. text.*; import java. awt.event.*; // An extension of SimpleEditor that adds styled-text features public class StyledEditor extends SimpleEditor{ public static void main(String[] args) {... order to "hook" into the Java virtual machine and interface with the application JavaSoft bundles the former with the Swing libraries The latter is distributed independently Another way of creating an assistive interface is to take advantage of the "Multi Look-and-Feel" with one or more Swing components For example, in addition to a graphical look-and-feel, you - 827 - Java Swing - O’Reilly might also... http:/ /java. sun.com/products/jfc for the latest and greatest Swing release, and word from the Swing team that the API has stabilized 24.1.25 RTFEditorKit One last editor kit provided by Swing is the RTFEditorKit , an extension of StyledEditorKit This kit knows how to read and write text using RTF (Rich Text Format), a generic format that many word processors are able to work with - 818 - Java Swing - O’Reilly Like HTMLEditorKit,... will not work with the java. io Reader and Writer classes 24.1.25.4 Generating RTF Output Because the version of write() that takes a Writer does nothing but throw an exception, you cannot generate RTF output by invoking the write() method on a JEditorPane (this method, defined in JTextComponent, takes a Writer and passes it through to the editor kit) Instead, you'll - 8 19 - Java Swing - O’Reilly need... simple example Consider the following HTML source: Swing HTML Demo Demonstration of JDK1.2beta HTML Package We will use this small HTML file to show how the Swing HTML pacakge models HTML text Here is a character attribute: This text is in italics. The O'Reilly Java Resource Center The element structure created... issues, you'll want to implement the following EditorKit methods: - 823 - Java Swing - O’Reilly public abstract Object clone() Strangely, the Swing implementations of this method just return a new instance of the editor kit subclass It is probably a good idea to return a "true clone" here, although this method is not currently used within Swing public void install( JEditorPane c) You only need to implement... on the Swing text framework If you've actually read it from beginning to end, congratulations! You now know everything there is to know about the powerful new Swing text architecture No matter what road you took to reach this final paragraph, it's important not to let all the complexity scare you away from using the Swing text components If you just need to do simple things, go back to Chapter 19, and... - Java Swing - O’Reilly 24.1.23 The HTML Package As we saw back in Chapter 19, when we introduced the JEditorPane class, Swing provides support for working with the web's most common markup language, HTML Supporting HTML is no small task In fact, there are over 10,000 lines of code in the JDK 1.2 beta 4 version of the javax .swing. text.html package, a number that will likely grow as the implementation . this chapter. // SimpleEditor .java // import javax .swing. *; import javax .swing. text.*; import java. awt.*; import java. io.*; import java. awt.event.*; import java. util.Hashtable; // An. TextActionExample .java // import javax .swing. *; import javax .swing. text.*; // Simple TextAction example public class TextActionExample { public static void main(String[] args) { Java Swing -. returned by these methods. // IOStyledEditor .java // import javax .swing. *; import javax .swing. text.*; import java. awt.event.*; import java. io.*; // An extension of StyledEditor

Ngày đăng: 12/08/2014, 19:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan