Adding icons to menu items

Okay, I'm a newbie at Java. I have a problem that I'm trying to solve. I added icons to the File menu item, that was easy, but how do I add icons to the other menu items? They are DefaultEditorKit. actions (cut copy paste undo redo) I can't seem to change their names either.

I'm also having problems with saving the changes I make in the text area.

Here's the whole code.

package components;

import java.awt.*;

import java.awt.event.*;

import java.util.HashMap;

import java.io.*;

import javax.swing.*;

import javax.swing.AbstractButton;

import javax.swing.text.*;

import javax.swing.event.*;

import javax.swing.undo.*;

publicclass TextComponentDemoextends JFrameimplements ActionListener{

JTextPane textPane;

AbstractDocument doc;

JTextArea changeLog;

JButton newButton, openButton, saveButton, undoButton, redoButton,/*cutButton, copyButton, pasteButton,*/ boldButton, italicButton, underlineButton;

protected String newline ="\n";

HashMap<Object, Action> actions;

File fFile =new File("default.txt");

JavaFilter fJavaFilter =new JavaFilter();

protected UndoAction undoAction;

protected RedoAction redoAction;

protected UndoManager undo =new UndoManager();

public TextComponentDemo(){

super("Notepad v1.0");

//Create the text pane and configure it.

textPane =new JTextPane();

textPane.setCaretPosition(0);

textPane.setMargin(new Insets(5,5,5,5));

StyledDocument styledDoc = textPane.getStyledDocument();

if (styledDocinstanceof AbstractDocument){

doc = (AbstractDocument)styledDoc;

}else{

System.err.println("Text pane's document isn't an AbstractDocument!");

System.exit(-1);

}

JScrollPane scrollPane =new JScrollPane(textPane);

scrollPane.setPreferredSize(new Dimension(600, 350));

newButton =new JButton ("", createImageIcon("images/new.png"));

newButton.setBackground(Color.white);

//newButton.setActionCommand("nou");

//newButton.addActionListener(this);

openButton =new JButton("", createImageIcon("images/open.png"));

openButton.setBackground(Color.white);

openButton.setActionCommand("deschide");

openButton.addActionListener(this);

saveButton =new JButton("", createImageIcon("images/save.png"));

saveButton.setBackground(Color.white);

saveButton.setActionCommand("salveaza");

saveButton.addActionListener(this);

Action actionBold =new StyledEditorKit.BoldAction();

actionBold.putValue(Action.NAME,"Bold");

boldButton =new JButton(actionBold);

boldButton.setBackground(Color.white);

Action actionItalic =new StyledEditorKit.ItalicAction();

actionItalic.putValue(Action.NAME,"Italic");

italicButton =new JButton(actionItalic);

italicButton.setBackground(Color.white);

Action actionUnderline =new StyledEditorKit.UnderlineAction();

actionUnderline.putValue(Action.NAME,"Underline");

underlineButton =new JButton(actionUnderline);

underlineButton.setBackground(Color.white);

String[] fontStrings ={"Arial","Arial Black","Comic Sans MS","Georgia","Serif","SansSerif","Times New Roman","Trebuchet MS","Verdana"};

JComboBox fontList =new JComboBox(fontStrings);

fontList.setSelectedIndex(0);

fontList.setBackground(Color.white);

fontList.setActionCommand("font");

fontList.addActionListener(this);

String[] sizeStrings ={"12","14","16","18","20","22","24","36","48"};

JComboBox sizeList =new JComboBox(sizeStrings);

sizeList.setSelectedIndex(0);

sizeList.setBackground(Color.white);

sizeList.setActionCommand("size");

sizeList.addActionListener(this);

JPanel buttonPanel =new JPanel();//use FlowLayout

buttonPanel.add(newButton);

buttonPanel.add(openButton);

buttonPanel.add(saveButton);

//buttonPanel.add(cutButton);

//buttonPanel.add(copyButton);

//buttonPanel.add(pasteButton);

buttonPanel.add(boldButton);

buttonPanel.add(italicButton);

buttonPanel.add(underlineButton);

buttonPanel.add(fontList);

buttonPanel.add(sizeList);

getContentPane().add(buttonPanel, BorderLayout.PAGE_START);

getContentPane().add(scrollPane, BorderLayout.CENTER);

//Set up the menu bar.

createActionTable(textPane);

JMenu fileMenu = createFileMenu();

JMenu editMenu = createEditMenu();

JMenu fontMenu = createFontMenu();

JMenu ajutorMenu = createAjutorMenu();

JMenuBar mb =new JMenuBar();

mb.add(fileMenu);

mb.add(editMenu);

mb.add(fontMenu);

mb.add(ajutorMenu);

setJMenuBar(mb);

//Start watching for undoable edits and caret changes.

doc.addUndoableEditListener(new MyUndoableEditListener());

}

//This one listens for edits that can be undone.

protectedclass MyUndoableEditListener

implements UndoableEditListener{

publicvoid undoableEditHappened(UndoableEditEvent e){

//Remember the edit and update the menus.

undo.addEdit(e.getEdit());

undoAction.updateUndoState();

redoAction.updateRedoState();

}

}

private ImageIcon createImageIcon (String fileName){

returnnew ImageIcon(fileName);

}

protected JMenu createFileMenu(){

JMenu menu =new JMenu("Fisier");

menu.setMnemonic(KeyEvent.VK_F);

JMenuItem menuItem;

ImageIcon iconNou =new ImageIcon("images/new.png");

menuItem =new JMenuItem("Nou", iconNou);

menuItem.setMnemonic(KeyEvent.VK_N);

menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));

//menuItem.setActionCommand("nou");

//menuItem.addActionListener(this);

menu.add(menuItem);

menu.addSeparator();

ImageIcon iconOpen =new ImageIcon("images/open.png");

menuItem =new JMenuItem("Deschide", iconOpen);

menuItem.setMnemonic(KeyEvent.VK_O);

menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));

menuItem.setActionCommand("deschide");

menuItem.addActionListener(this);

menu.add(menuItem);

ImageIcon iconSave =new ImageIcon("images/save.png");

menuItem =new JMenuItem("Salveaza", iconSave);

menuItem.setMnemonic(KeyEvent.VK_S);

menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));

menuItem.setActionCommand("deschide");

menuItem.addActionListener(this);

menu.add(menuItem);

menu.addSeparator();

ImageIcon iconQuit =new ImageIcon("images/quit.png");

menuItem =new JMenuItem("Iesire", iconQuit);

menuItem.setMnemonic(KeyEvent.VK_Q);

menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));

menuItem.setActionCommand("iesire");

menuItem.addActionListener(this);

menu.add(menuItem);

return menu;

}

publicvoid actionPerformed(ActionEvent e){

boolean status =false;

/* if ("nou".equals(e.getActionCommand())) {

nou();

}*/

if ("deschide".equals(e.getActionCommand())){

status = openFile();

if(!status)

JOptionPane.showMessageDialog(

null,

"Eroare la deschiderea fisierului!","Fisierul nu a putut fi deschis.",

JOptionPane.ERROR_MESSAGE

);

}

/* if ("salveaza".equals(e.getActionCommand())) {

status = saveFile();

if(!status)

JOptionPane.showMessageDialog(

null,

"Eroare IO in salvarea fisierului!", "Fisierul nu a putut fi salvat.",

JOptionPane.ERROR_MESSAGE

);

}*/

if ("iesire".equals(e.getActionCommand())){

System.exit(-1);

}

if ("font".equals(e.getActionCommand())){

JComboBox cb = (JComboBox)e.getSource();

String fontName = (String)cb.getSelectedItem();

String t =new String(textPane.getSelectedText());

//t.setText("fontName");

//t.setFont(new java.awt.Font(fontName, 0, 12));

//StyledEditorKit.FontFamilyAction font = new StyledEditorKit.FontFamilyAction(fontName, fontName);

}

}

boolean openFile(){

JFileChooser fc =new JFileChooser();

fc.setDialogTitle("Deschide Fisier");

fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

fc.setCurrentDirectory(new File ("."));

fc.setFileFilter(fJavaFilter);

int result = fc.showOpenDialog(this);

if(result == JFileChooser.CANCEL_OPTION){

returntrue;

}

elseif(result == JFileChooser.APPROVE_OPTION){

fFile = fc.getSelectedFile();

String file_string = readFile(fFile);

if(file_string !=null){

textPane.setText(file_string);

}

else

returnfalse;

}

else{

returnfalse;

}

returntrue;

}

public String readFile (File file){

StringBuffer fileBuffer;

String fileString=null;

String line;

try{

FileReader in =new FileReader (file);

BufferedReader dis =new BufferedReader (in);

fileBuffer =new StringBuffer () ;

while ((line = dis.readLine ()) !=null){

fileBuffer.append (line +"\n");

}

in.close ();

fileString = fileBuffer.toString ();

}

catch (IOException e ){

returnnull;

}

return fileString;

}

/* boolean saveFile () {

File file = null;

JFileChooser fc = new JFileChooser ();

fc.setCurrentDirectory (new File ("."));

fc.setFileFilter (fJavaFilter);

fc.setSelectedFile (fFile);

int result = fc.showSaveDialog (this);

if (result == JFileChooser.CANCEL_OPTION) {

return true;

} else if (result == JFileChooser.APPROVE_OPTION) {

fFile = fc.getSelectedFile ();

if (fFile.exists ()) {

int response = JOptionPane.showConfirmDialog (null,

"Overwrite existing file?","Confirm Overwrite",

JOptionPane.OK_CANCEL_OPTION,

JOptionPane.QUESTION_MESSAGE);

if (response == JOptionPane.CANCEL_OPTION) return false;

}

return writeFile (fFile, textPane.getText ());

} else {

return false;

}

}*/

protected JMenu createEditMenu(){

JMenu menu =new JMenu("Editare");

menu.setMnemonic(KeyEvent.VK_E);

JMenuItem menuItem;

undoAction=new UndoAction();

menu.add(undoAction);

redoAction =new RedoAction();

menu.add(redoAction);

menu.addSeparator();

menu.add(getActionByName(DefaultEditorKit.cutAction));

menu.add(getActionByName(DefaultEditorKit.copyAction));

menu.add(getActionByName(DefaultEditorKit.pasteAction));

menu.addSeparator();

menu.add(getActionByName(DefaultEditorKit.selectAllAction));

return menu;

}

//Create the style menu.

protected JMenu createFontMenu(){

JMenu menu =new JMenu("Font");

menu.setMnemonic(KeyEvent.VK_F);

JMenu subMenu =new JMenu ("Stil ");

Action action =new StyledEditorKit.BoldAction();

action.putValue(Action.NAME,"Bold");

subMenu.add(action);

action =new StyledEditorKit.ItalicAction();

action.putValue(Action.NAME,"Italic");

subMenu.add(action);

action =new StyledEditorKit.UnderlineAction();

action.putValue(Action.NAME,"Underline");

subMenu.add(action);

menu.add(subMenu);

menu.addSeparator();

JMenu subMenu2 =new JMenu ("Marime ");

subMenu2.add(new StyledEditorKit.FontSizeAction("12", 12));

subMenu2.add(new StyledEditorKit.FontSizeAction("14", 14));

subMenu2.add(new StyledEditorKit.FontSizeAction("16", 16));

subMenu2.add(new StyledEditorKit.FontSizeAction("18", 18));

subMenu2.add(new StyledEditorKit.FontSizeAction("20", 20));

subMenu2.add(new StyledEditorKit.FontSizeAction("22", 22));

subMenu2.add(new StyledEditorKit.FontSizeAction("24", 24));

subMenu2.add(new StyledEditorKit.FontSizeAction("36", 36));

subMenu2.add(new StyledEditorKit.FontSizeAction("48", 48));

menu.add(subMenu2);

menu.addSeparator();

JMenu subMenu3 =new JMenu ("Familie ");

subMenu3.add(new StyledEditorKit.FontFamilyAction("Arial","Arial"));

subMenu3.add(new StyledEditorKit.FontFamilyAction("Arial Black","Arial Black"));

subMenu3.add(new StyledEditorKit.FontFamilyAction("Comic Sans MS","Comic Sans MS"));

subMenu3.add(new StyledEditorKit.FontFamilyAction("Georgia","Georgia"));

subMenu3.add(new StyledEditorKit.FontFamilyAction("Serif","Serif"));

subMenu3.add(new StyledEditorKit.FontFamilyAction("SansSerif","SansSerif"));

subMenu3.add(new StyledEditorKit.FontFamilyAction("Times New Roman","Times New Roman"));

subMenu3.add(new StyledEditorKit.FontFamilyAction("Trebuchet MS","Trebuchet MS"));

subMenu3.add(new StyledEditorKit.FontFamilyAction("Verdana","Verdana"));

menu.add(subMenu3);

menu.addSeparator();

JMenu subMenu4 =new JMenu ("Culoare ");

subMenu4.add(new StyledEditorKit.ForegroundAction("Rosu", Color.red));

subMenu4.add(new StyledEditorKit.ForegroundAction("Verde", Color.green));

subMenu4.add(new StyledEditorKit.ForegroundAction("Albastru", Color.blue));

subMenu4.add(new StyledEditorKit.ForegroundAction("Galben", Color.yellow));

subMenu4.add(new StyledEditorKit.ForegroundAction("Gri", Color.gray));

subMenu4.add(new StyledEditorKit.ForegroundAction("Gri inchis", Color.darkGray));

subMenu4.add(new StyledEditorKit.ForegroundAction("Negru", Color.black));

menu.add(subMenu4);

return menu;

}

protected JMenu createAjutorMenu(){

JMenu menu =new JMenu("Ajutor");

menu.setMnemonic(KeyEvent.VK_J);

return menu;

}

privatevoid createActionTable(JTextComponent textComponent){

actions =new HashMap<Object, Action>();

Action[] actionsArray = textComponent.getActions();

for (int i = 0; i < actionsArray.length; i++){

Action a = actionsArray[i];

actions.put(a.getValue(Action.NAME), a);

}

}

private Action getActionByName(String name){

return actions.get(name);

}

class UndoActionextends AbstractAction{

public UndoAction(){

super("Undo");

setEnabled(false);

}

publicvoid actionPerformed(ActionEvent e){

try{

undo.undo();

}catch (CannotUndoException ex){

System.out.println("Unable to undo: " + ex);

ex.printStackTrace();

}

updateUndoState();

redoAction.updateRedoState();

}

protectedvoid updateUndoState(){

if (undo.canUndo()){

setEnabled(true);

putValue(Action.NAME, undo.getUndoPresentationName());

}else{

setEnabled(false);

putValue(Action.NAME,"Undo");

}

}

}

class RedoActionextends AbstractAction{

public RedoAction(){

super("Redo");

setEnabled(false);

}

publicvoid actionPerformed(ActionEvent e){

try{

undo.redo();

}catch (CannotRedoException ex){

System.out.println("Unable to redo: " + ex);

ex.printStackTrace();

}

updateRedoState();

undoAction.updateUndoState();

}

protectedvoid updateRedoState(){

if (undo.canRedo()){

setEnabled(true);

putValue(Action.NAME, undo.getRedoPresentationName());

}else{

setEnabled(false);

putValue(Action.NAME,"Redo");

}

}

}

privatestaticvoid createAndShowGUI(){

final TextComponentDemo frame =new TextComponentDemo();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setVisible(true);

}

publicstaticvoid main(String[] args){

SwingUtilities.invokeLater(new Runnable(){

publicvoid run(){

UIManager.put("swing.boldMetal", Boolean.FALSE);

createAndShowGUI();

}

});

}

}

class JavaFilterextends javax.swing.filechooser.FileFilter

{

publicboolean accept (File f){

return f.getName ().toLowerCase ().endsWith (".txt")

|| f.isDirectory ();

}

public String getDescription (){

return"Fisiere text (*.txt)";

}

}

[29558 byte] By [Norbert-a] at [2007-11-27 8:34:13]
# 1

Hi,

unfortunatly you cannot change the properties of Action object as you would do with JavaBeans. Instead you have to use the 'put' method.

eg.:

myAction.put(Action.SMALL_ICON, new ImageIcon(...));

IMHO this was a bad decision, because it's not like the JavaBeans standard and you loose static type information. :-/

-Puce

Message was edited by:

Puce

Pucea at 2007-7-12 20:30:25 > top of Java-index,Desktop,Core GUI APIs...