30. september 2002 - 12:05
#3
Du skal benytte JTextPane for at kunne indsætte billeder og
formattere teksten. Hvis du kun bruger html kan du godt
nøjes med JEditorPane. Her er et simpelt eksempel på en klasse der
er nedarver fra JTextPane hvor du kan formattere teksten interaktivt.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.io.*;
/**
* The FormattePane class is an extension of the
* JTextPane class with key short cuts for formatted text.<br>
* The following list explains the key sequences used:
* <ul>
* <li> CTRL-b bold text
* <li> CTRL-i italic text
* <li> CTRL-u underline text
* <li> CTRL-d strike through text
* <li> CTRL-1 superscript text
* <li> CTRL-2 subscript text
* <li> CTRL-x cut text
* <li> CTRL-c copy text
* <li> CTRL-v paste text
* <li> CTRL-C pick color
* <li> CTRL-I insert image
* <li> CTRL-L left align text
* <li> CTRL-R right align text
* <li> CTRL-M middle align text
* <li> CTRL-P allows the visible text to be printed.
* </ul>
* @version 1.0
* @author Carsten Knudsen
**/
public class FormattedPane
extends JTextPane
implements KeyListener, Serializable {
private JTextPane textArea = this;
/**
* Public constructor for class FormattedPane.
**/
public FormattedPane() {
setCaretPosition( 0 );
setMargin( new Insets( 0, 0, 0, 0 ) );
setupActions();
addKeyListener( this );
//ComponentPrinter.makePrintable( this );
} // constructor
private void selectFont() {
Font font = FontChooser.getSelectedFont( null );
if ( font != null ) {
Action action = new StyledEditorKit.FontFamilyAction( "dummy", font.getFamily() );
action.actionPerformed( new ActionEvent( this, 0, "" ) );
action = new StyledEditorKit.FontSizeAction( "dummy", font.getSize() );
action.actionPerformed( new ActionEvent( this, 0, "" ) );
} // if
} // selectFont
private void selectColor() {
Color color = JColorChooser.showDialog( null,
"Select color",
Color.white );
if ( color != null ) {
Action action = new StyledEditorKit.ForegroundAction( "dummy", color );
action.actionPerformed( new ActionEvent( this, 0, "" ) );
} // if
} // selectColor
private void selectImage() {
JFileChooser chooser = new JFileChooser();
int status = chooser.showOpenDialog( null );
if ( status == JFileChooser.APPROVE_OPTION ) {
File file = chooser.getSelectedFile();
Icon icon = new ImageIcon( file.getAbsolutePath() );
insertIcon( icon );
} // if
} // selectImage
/**
* The method setupActions registers all Actions.
* The method should always be invoked after deserializing
* a FormattedPane object.
**/
public void setupActions() {
// BOLD
Action boldAction = new StyledEditorKit.BoldAction();
boldAction.putValue( Action.NAME, "Bold" );
KeyStroke bStroke = KeyStroke.getKeyStroke( KeyEvent.VK_B, Event.CTRL_MASK );
registerKeyboardAction( boldAction,
"b",
bStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// ITALIC
Action italicAction = new StyledEditorKit.ItalicAction();
italicAction.putValue( Action.NAME, "Italic" );
KeyStroke iStroke = KeyStroke.getKeyStroke( KeyEvent.VK_I, Event.CTRL_MASK );
registerKeyboardAction( italicAction,
"i",
iStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// UNDERLINE
Action underlineAction = new StyledEditorKit.UnderlineAction();
underlineAction.putValue( Action.NAME, "Underline" );
KeyStroke uStroke = KeyStroke.getKeyStroke( KeyEvent.VK_U, Event.CTRL_MASK );
registerKeyboardAction( underlineAction,
"u",
uStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// CUT
Action cutAction = new DefaultEditorKit.CutAction();
cutAction.putValue( Action.NAME, "Cut" );
KeyStroke xStroke = KeyStroke.getKeyStroke( KeyEvent.VK_X, Event.CTRL_MASK );
registerKeyboardAction( cutAction,
"x",
xStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// COPY
Action copyAction = new DefaultEditorKit.CopyAction();
copyAction.putValue( Action.NAME, "Copy" );
KeyStroke cStroke = KeyStroke.getKeyStroke( KeyEvent.VK_C, Event.CTRL_MASK );
registerKeyboardAction( copyAction,
"c",
cStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// PASTE
Action pasteAction = new DefaultEditorKit.PasteAction();
pasteAction.putValue( Action.NAME, "Paste" );
KeyStroke vStroke = KeyStroke.getKeyStroke( KeyEvent.VK_V, Event.CTRL_MASK );
registerKeyboardAction( pasteAction,
"v",
vStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// ALIGNMENT
Action alignAction = new StyledEditorKit.AlignmentAction( "alignright",
StyleConstants.ALIGN_RIGHT );
alignAction.putValue( Action.NAME, "alignright" );
KeyStroke RStroke = KeyStroke.getKeyStroke( KeyEvent.VK_R,
Event.CTRL_MASK | Event.SHIFT_MASK );
registerKeyboardAction( alignAction,
"R",
RStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
alignAction = new StyledEditorKit.AlignmentAction( "alignleft",
StyleConstants.ALIGN_LEFT );
alignAction.putValue( Action.NAME, "alignleft" );
KeyStroke LStroke = KeyStroke.getKeyStroke( KeyEvent.VK_L,
Event.CTRL_MASK | Event.SHIFT_MASK );
registerKeyboardAction( alignAction,
"L",
LStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
alignAction = new StyledEditorKit.AlignmentAction( "alignmiddle",
StyleConstants.ALIGN_CENTER );
alignAction.putValue( Action.NAME, "alignmiddle" );
KeyStroke MStroke = KeyStroke.getKeyStroke( KeyEvent.VK_M,
Event.CTRL_MASK | Event.SHIFT_MASK );
registerKeyboardAction( alignAction,
"M",
MStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// FONT
Action fontAction = new AbstractAction() {
public void actionPerformed( ActionEvent ae ) {
selectFont();
} // actionPerformed
};
fontAction.putValue( Action.NAME, "Font" );
KeyStroke fStroke = KeyStroke.getKeyStroke( KeyEvent.VK_F, Event.CTRL_MASK );
registerKeyboardAction( fontAction,
"f",
fStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// COLOR
Action colorAction = new AbstractAction() {
public void actionPerformed( ActionEvent ae ) {
selectColor();
} // actionPerformed
};
colorAction.putValue( Action.NAME, "Color" );
KeyStroke CStroke = KeyStroke.getKeyStroke( KeyEvent.VK_C,
Event.CTRL_MASK | Event.SHIFT_MASK );
registerKeyboardAction( colorAction,
"C",
CStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// IMAGE
Action imageAction = new AbstractAction() {
public void actionPerformed( ActionEvent ae ) {
selectImage();
} // actionPerformed
};
imageAction.putValue( Action.NAME, "Image" );
KeyStroke IStroke = KeyStroke.getKeyStroke( KeyEvent.VK_I,
Event.CTRL_MASK | Event.SHIFT_MASK );
registerKeyboardAction( imageAction,
"I",
IStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// DELETE
Action deleteAction = new AbstractAction() {
public void actionPerformed( ActionEvent ae ) {
MutableAttributeSet attr = new SimpleAttributeSet();
Object attribute = StyleConstants.CharacterConstants.StrikeThrough;
attr.addAttribute( attribute, new Boolean( true ) );
setCharacterAttributes( attr, true );
} // actionPerformed
};
deleteAction.putValue( Action.NAME, "Delete" );
KeyStroke DStroke = KeyStroke.getKeyStroke( KeyEvent.VK_D,
Event.CTRL_MASK );
registerKeyboardAction( deleteAction,
"D",
DStroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// DELETE
Action delete1Action = new AbstractAction() {
public void actionPerformed( ActionEvent ae ) {
MutableAttributeSet attr = new SimpleAttributeSet();
Object attribute = StyleConstants.CharacterConstants.StrikeThrough;
attr.addAttribute( attribute, new Boolean( false ) );
setCharacterAttributes( attr, true );
} // actionPerformed
};
deleteAction.putValue( Action.NAME, "Delete1" );
KeyStroke D1Stroke = KeyStroke.getKeyStroke( KeyEvent.VK_D,
Event.CTRL_MASK | Event.SHIFT_MASK );
registerKeyboardAction( delete1Action,
"D",
D1Stroke,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// SUPERSCRIPT
Action superAction = new AbstractAction() {
public void actionPerformed( ActionEvent ae ) {
MutableAttributeSet attr = new SimpleAttributeSet();
Object attribute = StyleConstants.CharacterConstants.Superscript;
attr.addAttribute( attribute, new Boolean( true ) );
setCharacterAttributes( attr, true );
} // actionPerformed
};
superAction.putValue( Action.NAME, "Super" );
KeyStroke Stroke1 = KeyStroke.getKeyStroke( KeyEvent.VK_1,
Event.CTRL_MASK );
registerKeyboardAction( superAction,
"1",
Stroke1,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
Action super1Action = new AbstractAction() {
public void actionPerformed( ActionEvent ae ) {
MutableAttributeSet attr = new SimpleAttributeSet();
Object attribute = StyleConstants.CharacterConstants.Superscript;
attr.addAttribute( attribute, new Boolean( false ) );
setCharacterAttributes( attr, true );
} // actionPerformed
};
super1Action.putValue( Action.NAME, "Super1" );
KeyStroke Stroke11 = KeyStroke.getKeyStroke( KeyEvent.VK_1,
Event.CTRL_MASK | Event.SHIFT_MASK );
registerKeyboardAction( super1Action,
"11",
Stroke11,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
// SUBSCRIPT
Action subAction = new AbstractAction() {
public void actionPerformed( ActionEvent ae ) {
MutableAttributeSet attr = new SimpleAttributeSet();
Object attribute = StyleConstants.CharacterConstants.Subscript;
attr.addAttribute( attribute, new Boolean( true ) );
setCharacterAttributes( attr, true );
} // actionPerformed
};
subAction.putValue( Action.NAME, "Sub" );
KeyStroke Stroke2 = KeyStroke.getKeyStroke( KeyEvent.VK_2,
Event.CTRL_MASK );
registerKeyboardAction( subAction,
"2",
Stroke2,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
Action sub1Action = new AbstractAction() {
public void actionPerformed( ActionEvent ae ) {
MutableAttributeSet attr = new SimpleAttributeSet();
Object attribute = StyleConstants.CharacterConstants.Subscript;
attr.addAttribute( attribute, new Boolean( false ) );
setCharacterAttributes( attr, true );
} // actionPerformed
};
sub1Action.putValue( Action.NAME, "Sub1" );
KeyStroke Stroke22 = KeyStroke.getKeyStroke( KeyEvent.VK_2,
Event.CTRL_MASK | Event.SHIFT_MASK );
registerKeyboardAction( sub1Action,
"2",
Stroke22,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
} // setupActions
// for inserting any Component
/*
JButton button = new JButton( "Button" );
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae ) {
System.out.println("Hi!");
}
} );
insertComponent( button );
*/
/////////////////////////////////////////////
// implementation of interface KeyListener //
/////////////////////////////////////////////
/**
* The String searchString contains the last String
* that was the target in a search operation.
**/
private String searchString = "";
private String replaceString = ""; // declared but is not remembered
/**
* The method keyPressed handles key events with the CTRL key pressed down.
* The following are supported:
* <ul>
* <li> CTRL-s starts a search operation from the current caret position.
* <li> CTRL-r starts a search and replace operation from the current caret position.
* </ul>
**/
public void keyPressed( KeyEvent e ) {
if ( e.getModifiers() == InputEvent.CTRL_MASK ) {
// search
if ( KeyEvent.getKeyText( e.getKeyCode() ).equals( "S" ) ) {
Color searchColor = Color.yellow;
JPanel panel = new JPanel();
JLabel textLabel = new JLabel( "Enter search string " );
JTextField textField = new JTextField( 20 );
textField.setText( searchString );
panel.add( textLabel );
panel.add( textField );
textField.requestFocus();
int result = JOptionPane.showConfirmDialog( this,
panel,
"Search",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE
);
if ( result == JOptionPane.OK_OPTION ) {
String text = textField.getText();
if ( ! text.equals( "" ) ) {
searchString = text;
int index = textArea.getCaretPosition();
int i = getText().indexOf( searchString, index );
if ( i >= 0 ) {
try {
textArea.setCaretPosition( i + 1 );
} // try
catch ( IllegalArgumentException iae ) {
} // catch
try {
Highlighter highlighter = textArea.getHighlighter();
highlighter.removeAllHighlights();
highlighter.addHighlight( i,
i + searchString.length(),
new DefaultHighlighter.DefaultHighlightPainter( searchColor ) );
} // try
catch ( BadLocationException ble ) {
} // catch
} // if
} // if
else {
Highlighter highlighter = textArea.getHighlighter();
highlighter.removeAllHighlights();
} // else
} // if
} // if, CTRL-S
// search and replace
else if ( KeyEvent.getKeyText( e.getKeyCode() ).equals( "R" ) ) {
JPanel panel = new JPanel();
JLabel stringLabel = new JLabel( "Enter string " );
JTextField stringField = new JTextField( 10 );
JLabel replaceLabel = new JLabel( " Enter replacement " );
JTextField replaceField = new JTextField( 10 );
stringField.setText( searchString );
panel.add( stringLabel );
panel.add( stringField );
panel.add( replaceLabel );
panel.add( replaceField );
int result = JOptionPane.showConfirmDialog( this,
panel,
"Search and replace",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE
);
if ( result == JOptionPane.OK_OPTION ) {
String text = stringField.getText();
if ( ! text.equals( "" ) ) {
searchString = text;
replaceString = replaceField.getText();
String newText = getText();
int index = textArea.getCaretPosition();
int i = newText.indexOf( searchString, index + 1 );
if ( i >= 0 ) {
Highlighter highlighter = textArea.getHighlighter();
highlighter.removeAllHighlights();
while ( i >= 0 ) {
newText = newText.substring( 0, i ) + replaceString +
newText.substring( i + searchString.length(),
newText.length() );
i += replaceString.length();
i = newText.indexOf( searchString, i );
}
setText( newText );
textArea.setCaretPosition( index );
} // if
} // if
else {
Highlighter highlighter = textArea.getHighlighter();
highlighter.removeAllHighlights();
} // else
} // if
} // else if, CTRL-R
textArea.requestFocus();
} // control handlers
}
/**
* The method keyReleased does nothing.
**/
public void keyReleased( KeyEvent e ) {
}
/**
* The method keyTyped does nothing.
**/
public void keyTyped( KeyEvent e ) {
}
} // FormattedPane