Results 1 to 3 of 3
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,038
    Rep Power
    8

    Default a font chooser example

    After studying one year java I started to try things and begun a small project of writing a text writer. The writer should have all basic functions and include RTF and images. I started with setting up the several menus and finished the file, edit and font menus (the more basic part of the GUI). At the moment I am working on two toolbars that will double some of the menu functions and add some more typical text writer stuff.

    I'd like to present it for comments and criticism the font menu. I tried to write it in a generic way so there is a simple Main class included for testing. (Put the 7 classes into a project called: fontchooser2)

    There are 6 classes involved of which four I wrote myself (ColerFillcon is of Kim Topley author of the FFC book and MenuScroller I got from the Net Menu Scroller « Java Tips Weblog).

    The base class, FontClass speaks for itself, all font families (String[]), styles (FontStyleKeyValue[]), sizes (String[]) and colors (HashMap) are derived from this class.

    The two MenuFontMenu classes do the actual work. The first one takes care of the font family and offers the user the opportunity to construct a Short-font-list-menu from the long All-font-list-menu. The second class takes care of the rest (style, size and color). Some of the menu items will also appear on a toolbar as buttons and combo boxes. (In case of the file menu I worked exclusively with action derived from the AbstractAction class and it was very easy just to add these actions to the toolbar and have the action code only once present).

    I should still look into how to comment the code in a more professional manner, so sorry for that part of the code (I first wanted to get the programming going).

    Java Code:
    package fontchooser2;
    
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.GraphicsEnvironment;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     *
     * @author willem
     */
    
    
    public class Fontclass {
    
    
        private String familyName, currentFont;
        private ArrayList <String> fontshortlist;
        private Font font;
        private int familyStyle, familySize;
        private Map <String,Object> fontStylenames;
        private FontStyleKeyValue[] fontstyleKeyValue;
        private Map<String, Color> colorMap;
    
        public Fontclass()  {
            fontStylenames = new HashMap<String,Object>();
        }
    
        public void getDefaultFontFields() {
            if (font != null) {
                familyName = font.getFamily();
                familyStyle = font.getStyle();
                familySize = font.getSize();
            }
        }
    
        /**
        * This important helper class sets the font family, style, size and color.
        * These main font atributes form the basis of the two MenuFontMenu classes
        * and the Toolbar class and its FontColorDialog helpers class
        * All font stuff is set in this class so it can be considered as the
        * base class of the application!
        *
        */
    
        public String[] getAllFontNames() {
            GraphicsEnvironment e =
                                GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[] fontNameList = e.getAvailableFontFamilyNames();
            return fontNameList;
        }
    
        
    
        public FontStyleKeyValue[] getAllFontStyles() {
            fontstyleKeyValue = new FontStyleKeyValue[] {
                new FontStyleKeyValue("Regular", Font.PLAIN),
                new FontStyleKeyValue("Bold", Font.BOLD),
                new FontStyleKeyValue("Italic", Font.ITALIC)};
            return fontstyleKeyValue;
            
        }
    
        public String[] getAllFontSizes() {
            String[] fontSizeList = new String[18];
            int count=0;
            for (int i = 6; i <= 11; i++) {
                fontSizeList[count] = "" + i;
                count++;
            }
            for (int i = 12; i <= 28; i += 2) {
                fontSizeList[count] = "" + i;
                count++;
            }
            fontSizeList[15] = "36";
            fontSizeList[16] = "48";
            fontSizeList[17] = "72";
    
            return fontSizeList;
        }
    
        public Map getColorList() {
             colorMap = new HashMap<String, Color>();
             colorMap.put("Black", Color.black);
             colorMap.put("Light Grey", Color.lightGray);
             colorMap.put("Grey", Color.gray);
             colorMap.put("Dark Grey", Color.darkGray);
             colorMap.put("Blue", Color.blue);
             colorMap.put("Red", Color.red);
             colorMap.put("Yellow", Color.yellow);
             colorMap.put("Green", Color.green);
             colorMap.put("Orange", Color.orange);
             colorMap.put("Magenta", Color.magenta);
             colorMap.put("Pink", Color.pink);
             colorMap.put("Cyan", Color.cyan);
             colorMap.put("White", Color.white);
    
             return colorMap;
        }
        
        public class FontStyleKeyValue { // helper class for font style
            private String key; // the style name
            private int value;  // the style contstant
            
            public FontStyleKeyValue(String key, int value) {
                this.key = key;
                this.value = value;
            }
            
            public String getFontStyleKey() {
                return key;
            }
            
            public int getFontStyleValue() {
                return value;
            }
            
        }
    }



    Java Code:
    package fontchooser2;
    
    import fontchooser2.MenuFontMenu2.ColorChangeAction;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.AbstractAction;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenu;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JMenuItem;
    import javax.swing.event.MenuListener;
    
    
    
    /**
     *
     * @author willem
     */
     class MenuFontMenu  {
    
         private Fontclass fontclass;
         private MenuFontMenu2 fontMenu2;
         private Font font;
         private IconImport iconImport;
         private Container textcanvas;
         private JRadioButtonMenuItem rbShortList, rbSetup, rbAllfonts;
         private ButtonGroup shortlistgroup;
         private int familyStyle, familySize;
         private String familyName, currentFont;
         private JMenu fontMenu, allFontMenu, selectFontMenu, shortFontMenu;
         private JMenuItem dummyItem;
    
         private String[] fontNameList, fontStyleList,
                                            fontSizeList, currentFontNameList;
         private JCheckBoxMenuItem[] checkbMenuList;
         private JRadioButtonMenuItem[] radiobAll, radiobShortlist;
         private Map <String,Object> shortMenuMap;
         private ColorChangeAction[] colorActions;
    
         private MenuActionListener menulistener;
         private MenuListener fontlistener;
    
        
    
         public MenuFontMenu(Container textcanvas) {
    
             // the text component reference
             this.textcanvas = textcanvas;
             iconImport = new IconImport("http://www.java-forums.org/images/");
    
             // Get the system fonts
             fontclass = new Fontclass();
             fontNameList = fontclass.getAllFontNames();
    
             shortlistgroup = new ButtonGroup();
        
             menulistener = new MenuActionListener();
             shortMenuMap = new HashMap<String,Object>();
    
             //font menu extention for setting style, size and color
             fontMenu2 = new MenuFontMenu2(textcanvas);
         }
    
         public String getCurrentFont()    {
             return currentFont;
         }
         public int getCurrentSize()    {
             return fontMenu2.getCurrentSize();
         }
    
         public int getCurrentStyle()    {
             return fontMenu2.getCurrentStyle();
         }
    
         public Color getCurrentColor()    {
             return fontMenu2.getCurrentColor();
         }
    
         public JMenu getMenu()    {
             return fontMenu;
         }
    
         public String[] getCurrentFontList()    {
             if (shortFontMenu == null)  {
                currentFontNameList =  fontNameList;
             } else {
                // Component comp;
                 Component[] comp = shortFontMenu.getComponents();
                 currentFontNameList = new String[comp.length];
                 for (int i=0; i < comp.length; i++) {
                     currentFontNameList[i] = "" + comp[i];
                 }
             }
             return currentFontNameList;
         }
    
         public ColorChangeAction[] getColorActions()  {
             return fontMenu2.getColorActions();
         }
    
    
         /**
         * Create the Font menu to support family, style, size and color
         * The family, style size and color elements are declared in
         * the Fontclass.
         * The buildFontMenu returns a populated menu: fontMenu
         * The variable currentFont contains the selected font family
         * The single font menu list gets removed and installed constantly
         * 1) for selection radio buttons 2) for setting up the short list
         * check boxes. The font family list is at the 4th position
         * of the font menu.
         * The second class MenuFontMenu2 adds the style size and color to
         * the menu (down part from postion 4)
         */
    
         public JMenu buildFontMenu() {
            // Action for Font menu items / the all font list
            AbstractAction allFontsAction = new AbstractAction() {
                {	// "Constructor"
                    putValue(NAME, "All Fonts");
                    putValue(SMALL_ICON, iconImport.getImageIcon("whatever"));
                    putValue(MNEMONIC_KEY, new Integer('N'));
                    putValue(SHORT_DESCRIPTION, "Creates a whatever");
                    putValue(LONG_DESCRIPTION, "Creating new whatever...");
                }
                public void actionPerformed(ActionEvent evt) { 
                    fontMenu.remove(4);
                    fontMenu.insert(allFontMenu, 4);
                    for (int i= 0; i < fontNameList.length; i++) { // remembering
                        radiobAll[i].setSelected(false); // previous selection
                        if (fontNameList[i].equals(currentFont)) { // short list
                            radiobAll[i].setSelected(true); 
                        }
                    }
                }
            };
            // the short font list after construction (see next block)
            AbstractAction shortListFontsAction = new AbstractAction() {
                {	
                    putValue(NAME, "Short Fontlist");
                    putValue(SMALL_ICON, iconImport.getImageIcon("whatever"));
                    putValue(MNEMONIC_KEY, new Integer('N'));
                    putValue(SHORT_DESCRIPTION, "Creates whatever");
                    putValue(LONG_DESCRIPTION, "Creating whatever...");
                }
                public void actionPerformed(ActionEvent evt) { 
                    fontMenu.remove(4);
                    fontMenu.insert(shortFontMenu, 4);
                    if (shortFontMenu.getItemCount() > 1 & currentFont != null)  {
                        shortlistgroup.clearSelection();
                        JRadioButtonMenuItem rb = (JRadioButtonMenuItem)
                                                shortMenuMap.get(currentFont);
                        if (rb != null)
                        rb.setSelected(true); // remembering
                    }                         // previous selection all list
                }
            };
            // constructing the short list see also makeShortFontlist
            // and MenuActionListener. the list is stored in shortMenuMap
            // and shortFontMenu
            AbstractAction setupshortListFontsAction = new AbstractAction() {
                {	
                    putValue(NAME, "Setup Shortlist");
                    putValue(SMALL_ICON, iconImport.getImageIcon("whatever"));
                    putValue(MNEMONIC_KEY, new Integer('N'));
                    putValue(SHORT_DESCRIPTION, "Creates a new whatever");
                    putValue(LONG_DESCRIPTION, "Creating new whatever...");
                }
                public void actionPerformed(ActionEvent evt) {
                    fontMenu.remove(4); // the selection is constructed at
                    fontMenu.insert(selectFontMenu, 4); // MenuActionListener
                } 
            };      
    
            // the several menus
            fontMenu = new JMenu("Fonts");
            ButtonGroup group = new ButtonGroup();
    
            // first the three fixed radio buttons All/ Short list/
            //selecting short list
            rbAllfonts = new JRadioButtonMenuItem(allFontsAction);
            rbAllfonts.setSelected(true);
            fontMenu.add(rbAllfonts);
            group.add(rbAllfonts);
    
            rbShortList = new JRadioButtonMenuItem(shortListFontsAction);
            rbShortList.setSelected(false);
            rbShortList.setEnabled(true);
            fontMenu.add(rbShortList);
            group.add(rbShortList);
    
            rbSetup = new JRadioButtonMenuItem(setupshortListFontsAction);
            rbSetup.setSelected(false);
            fontMenu.add(rbSetup);
            group.add(rbSetup);
            fontMenu.addSeparator();
    
            // a second menu added to show the font listings All/Short
            allFontMenu = new JMenu("Font List");
            selectFontMenu = new JMenu("Font List");
            shortFontMenu = new JMenu("Font List");
    
            buildFontMenuItems(fontNameList);
            dummyItem = new  JMenuItem("empty");
            dummyItem.setEnabled(false);
            shortFontMenu.add(dummyItem);
            fontMenu.add(allFontMenu);
    
            MenuScroller.setScrollerFor(allFontMenu);
            MenuScroller.setScrollerFor(selectFontMenu);
            // the menus of the extions from the class MenuFontMenu2
            fontMenu.addSeparator();// the addional font menus of style, size and
            fontMenu.add(fontMenu2.buildFontMenu2(fontMenu)); // color
    
            return fontMenu; // returns the populated menu
         }
    
         class MenuActionListener implements ActionListener{
            public void actionPerformed(ActionEvent evt) {
                Object menusource = evt.getSource();
                String cmd = evt.getActionCommand();
                if (rbSetup.isSelected()){ // here setup the font short list
                    makeShortFontlist(evt);
                } else { // here: readout the font family selection
                    currentFont = cmd;
                    System.out.println("\naction: " + currentFont);
    
                }
    
                if (shortFontMenu.getItemCount() > 0) { // removing the dummy of the
                    shortFontMenu.remove(dummyItem);    // empty short list
                } else {
                     shortFontMenu.add(dummyItem);
                }
            }
         }
         // building all radio buttons and checkboxes for selection (done only once)
         public void buildFontMenuItems(String[] names)  { 
              radiobAll = new JRadioButtonMenuItem[names.length];
              radiobShortlist = new JRadioButtonMenuItem[names.length];
              checkbMenuList = new JCheckBoxMenuItem[names.length];
              ButtonGroup allFontgroup = new ButtonGroup();
              Font ft = fontMenu.getFont();
              Font font;
              //the names-array contains all font families see FontClass
              for (int i = 0; i < names.length; i++) { 
                    font = new Font(names[i], Font.PLAIN, 16);
                    radiobAll[i] = new JRadioButtonMenuItem(names[i]);
                    checkbMenuList[i] = new JCheckBoxMenuItem(names[i]);
    
                    radiobAll[i].setActionCommand(names[i]);
                    checkbMenuList[i].setActionCommand(names[i]);
    
                    radiobAll[i].setFont(font);
                    checkbMenuList[i].setFont(font);
    
                    allFontgroup.add(radiobAll[i]);
    
                    radiobAll[i].addActionListener(menulistener);
                    checkbMenuList[i].addActionListener(menulistener);
    
                    selectFontMenu.add(checkbMenuList[i]);
                    allFontMenu.add(radiobAll[i]);
              }
              allFontMenu.setFont(ft);
              selectFontMenu.setFont(ft);
         }
    
         // this method gets called when selecting the font families for the
         // short font menu list stored in: shortMenuMap and shortFontMenu
         // this menu gets removed and installed at the 4th position of the font menu
         public void makeShortFontlist(ActionEvent evt)  { 
            String cmd = evt.getActionCommand();           
            JRadioButtonMenuItem rb;
            Font ft = fontMenu.getFont();
            Font font;
            for (int i = 0; i < fontNameList.length; i++) {
                String s = checkbMenuList[i].getActionCommand();
                if  (cmd.equals(s)) {
                    if (checkbMenuList[i].isSelected()) {   // adding onto the list
                        font = new Font(s, Font.PLAIN, 16); // when selected
                        rb = new JRadioButtonMenuItem(s);
                        rb.setActionCommand(s);
                        rb.addActionListener(menulistener);
                        rb.setFont(font);
                        shortlistgroup.add(rb);
                        shortFontMenu.add(rb);
                        shortMenuMap.put(s, rb);
                      
                    } else { // removing from the list
                        rb = (JRadioButtonMenuItem) shortMenuMap.get(s);
                        shortMenuMap.remove(s);
                        shortlistgroup.remove(rb);
                        shortFontMenu.remove(rb);
                    }
                }
            }
            shortFontMenu.setFont(ft);
         }
    }


    Java Code:
    package fontchooser2;
    
    
    
    import fontchooser2.Fontclass.FontStyleKeyValue;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;
    import javax.swing.AbstractAction;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenu;
    import javax.swing.JPanel;
    import javax.swing.JRadioButtonMenuItem;
    
    
    /**
     *
     * @author willem
     */
     class MenuFontMenu2 extends JPanel {
    
         private IconImport iconImport;
         private Container textcanvas;
         private Fontclass fontclass;
         private String[]  fontSizeList;
         private ColorChangeAction[] colorActions;
         private MenuStyleAction menuStyleAction;
         private String currentColor;
         private int currentSize, currentStyle;
         private Color color;
         private FontStyleKeyValue[] fontStyleList;
         private Map<String, Color> colorMap;
      //   private FontStyle fontstyle;
    
         public MenuFontMenu2(Container textcanvas) {
            this.textcanvas = textcanvas;
            iconImport = new IconImport("http://www.java-forums.org/images/");
            // Get all the system fonts
            fontclass = new Fontclass();
            fontStyleList = fontclass.getAllFontStyles();
            fontSizeList = fontclass.getAllFontSizes();
            colorMap = fontclass.getColorList();
    
         }
    
         /**
         * MenuFontMenu2
         * creates the Font menu to support style, size and color it is
         * the extention of the MenuFontMenu class and
         * Sets the lower part of the font menu
         */
         public int getCurrentSize()    {
             return currentSize;
         }
    
         public int getCurrentStyle()    {
             return currentStyle;
         }
    
         public Color getCurrentColor()    {
             return color;
         }
    
         public ColorChangeAction[] getColorActions()  {
             return colorActions;
         }
    
         public JMenu buildFontMenu2(JMenu jm) {      // the previous font class
                                                      // sets the reference (jm) for
             //the fontstyle menu added                  extending the menu list
             JMenu fontStyle = new JMenu("Font Style");
             menuStyleAction = new MenuStyleAction("");
             Font font;
             Font ft = jm.getFont();
             JRadioButtonMenuItem rbStyle;
             ButtonGroup buttongroupStyle = new ButtonGroup();
    
             for (int i=0; i < fontStyleList.length; i++) { // the style menu
                font = new Font("" + ft, fontStyleList[i].getFontStyleValue(), 16);
                rbStyle = new JRadioButtonMenuItem(fontStyleList[i].getFontStyleKey());
                rbStyle.setFont(font);
                rbStyle.setActionCommand("" + fontStyleList[i].getFontStyleKey());
                rbStyle.addActionListener(menuStyleAction);
                buttongroupStyle.add(rbStyle);
                fontStyle.add(rbStyle);
             }
             jm.add(fontStyle);
    
             //the font size menu added
             JMenu fontSize = new JMenu("Font Size");
             ft = jm.getFont();
             JRadioButtonMenuItem rbSize;
             ButtonGroup buttongroupSize = new ButtonGroup();
    
             for (int i=0; i < fontSizeList.length; i++) { // the font size menu
                rbSize = new JRadioButtonMenuItem(fontSizeList[i]);
                rbSize.setActionCommand(fontSizeList[i]);
                rbSize.addActionListener(menuStyleAction);
                buttongroupSize.add(rbSize);
                fontSize.add(rbSize);
             }
             jm.add(fontSize);
    
             //the color menu added
             JMenu fontColor = new JMenu("Font Color");
             ft = jm.getFont();
             JRadioButtonMenuItem rbColor;
    
             int size = colorMap.size();
             colorActions = new ColorChangeAction[size];
    
             Set entries = colorMap.entrySet();
             Iterator iter = entries.iterator();
             int count = 0;
             while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry)iter.next();
                String key = (String) entry.getKey();
                Color value = (Color) entry.getValue();
                colorActions[count] = new ColorChangeAction(key, value);
                count++;
              }
    
             ButtonGroup buttongroupColor = new ButtonGroup();
              for (int i=0; i < colorActions.length; i++) { // setting the colors
                rbColor = new JRadioButtonMenuItem(colorActions[i]);
                buttongroupColor.add(rbColor);
                fontColor.add(rbColor);
             }
    
            
            jm.add(fontColor);
    
            return jm;
         }
    
        // the action for the choosen color
        class ColorChangeAction extends AbstractAction {
            ColorChangeAction(String name, Color color) { // color name and color
                                                // size of icon + border
                super(name, new ColorFillIcon(color, 15, 10, 1));
                this.color = color;     
            }
            // Action to take when this color is selected
            public void actionPerformed(ActionEvent evt) {
                System.out.println("Color chosen: " + color);
                
            }
            Color color;
        }
        // the actions for font style and size
        class MenuStyleAction extends AbstractAction {
                public MenuStyleAction(String name) {
                    putValue(NAME, name);
                    putValue(SMALL_ICON, iconImport.getImageIcon("whatever"));
                    putValue(MNEMONIC_KEY, new Integer('N'));
                    putValue(SHORT_DESCRIPTION, "Creates whatever");
                    putValue(LONG_DESCRIPTION, "Creating whatever...");
                }
    
    	    public void actionPerformed(ActionEvent evt) {
    		 Object menusource = evt.getSource();
                     String cmd = evt.getActionCommand();
                     // sets the current font style
                     for (int i=0; i < fontStyleList.length; i++) {
                         if (cmd.equals(fontStyleList[i].getFontStyleKey())) {
                            currentStyle = fontStyleList[i].getFontStyleValue();
                            System.out.println("Font Style: " + currentStyle
                                                    + " string " + cmd);
    
                         }
                     }
                     // sets the current font size
                     for (int i=0; i < fontSizeList.length; i++) {
                         if (cmd.equals(fontSizeList[i])) {
                            currentSize = Integer.parseInt(fontSizeList[i]);
                            System.out.println("Font Size: " + currentSize);
    
                         }
                     }
    	    }
        }
    
    }
    Last edited by willemjav; 01-24-2014 at 09:54 AM.

  2. #2
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,038
    Rep Power
    8

    Default Re: a font chooser example

    and here are the helper classes:

    Java Code:
    /*
     * from the JFC book author Kim Topley
     */
    
    package fontchooser2;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class ColorFillIcon implements Icon {
        public ColorFillIcon(Color fill,
                                int width,
                                int height,
                                int borderSize) {
            this.fillColor      = fill;
            this.borderSize     = borderSize;
            this.width      = width;
            this.height     = height;
            this.shadow     = Color.black;
            this.fillWidth      = width - 2 * borderSize;
            this.fillHeight     = height - 2 * borderSize;   
            //this.fillWidth        = width ;
            //this.fillHeight       = height;
        }
    
        public ColorFillIcon(Color fill, int size) {
            this(fill, size, size, BORDER_SIZE);
        }
    
        public ColorFillIcon(Color fill) {
            this(fill, DEFAULT_WIDTH, DEFAULT_HEIGHT, BORDER_SIZE);
        }
    
        // Set non-default shadow color
        public void setShadow(Color c){
            shadow = c;
        }
    
        // Change the main color
        public void setFillColor(Color c) {
            fillColor = c;
        }
    
        // The Icon interface
        public int getIconWidth() {
            return width;
        }
    
        public int getIconHeight() {
            return height;
        }
    
        public void paintIcon(Component comp, Graphics g, int x, int y) {
            Color c = g.getColor();
    
            // Draw the border
            if (borderSize > 0) {
                g.setColor(shadow);
                for (int i = 0; i < borderSize; i++) {
                    g.drawRect(x + i, y + i, width - 2 * i - 1, height - 2 * i - 1);
                }
            }
    
            // Fill the remainder of the icon
            g.setColor(fillColor);
            g.fillRect(x + borderSize, y + borderSize, fillWidth, fillHeight);
            g.setColor(c);
    
        }
    
        // Icon state
        protected int width;        // Color fill width
        protected int height;       // Color fill height
        protected Color fillColor;  // Color to fill with
        protected Color shadow;     // Shadow color
        protected int borderSize;   // Border size in pixels
        protected int fillHeight;   // Height of area to fill
        protected int fillWidth;    // Width of area to fill
    
        // Constants
        public static final int BORDER_SIZE = 2;
        //public static final int DEFAULT_SIZE = 32;
            public static final int DEFAULT_WIDTH= 50;
            public static final int DEFAULT_HEIGHT= 32;
    }


    Java Code:
    package fontchooser2;
    
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    
    /**
     *
     * @author willem
     */
     class IconImport {
    
        String iconPath;
    
        public IconImport(String iconPath) {
            this.iconPath = iconPath;
        }
    
    
        public Icon getImageIcon(String filename)  {
                Icon icon = null;
                try {
                    icon = new
                    ImageIcon(getClass().getResource(iconPath + filename));
                }
                catch(NullPointerException n)  {
                    System.out.println("file not found <" + filename + ">");
                }
                return icon;
        }
    }


    Java Code:
    package fontchooser2;
    
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseWheelEvent;
    import java.awt.event.MouseWheelListener;
    import javax.swing.Icon;
    import javax.swing.JComponent;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.MenuSelectionManager;
    import javax.swing.Timer;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.event.PopupMenuEvent;
    import javax.swing.event.PopupMenuListener;
    
    /**
     * A class that provides scrolling capabilities to a long menu dropdown or
     * popup menu.  A number of items can optionally be frozen at the top and/or
     * bottom of the menu.
     * <P>
     * <B>Implementation note:</B>  The default number of items to display
     * at a time is 15, and the default scrolling interval is 125 milliseconds.
     * <P>
     *
     * @version 1.5.0 04/05/12
     * @author Darryl
     */
    public class MenuScroller {
    
      //private JMenu menu;
      private JPopupMenu menu;
      private Component[] menuItems;
      private MenuScrollItem upItem;
      private MenuScrollItem downItem;
      private final MenuScrollListener menuListener = new MenuScrollListener();
      private int scrollCount;
      private int interval;
      private int topFixedCount;
      private int bottomFixedCount;
      private int firstIndex = 0;
      private int keepVisibleIndex = -1;
    
      /**
       * Registers a menu to be scrolled with the default number of items to
       * display at a time and the default scrolling interval.
       *
       * @param menu the menu
       * @return the MenuScroller
       */
      public static MenuScroller setScrollerFor(JMenu menu) {
        return new MenuScroller(menu);
      }
    
      /**
       * Registers a popup menu to be scrolled with the default number of items to
       * display at a time and the default scrolling interval.
       *
       * @param menu the popup menu
       * @return the MenuScroller
       */
      public static MenuScroller setScrollerFor(JPopupMenu menu) {
        return new MenuScroller(menu);
      }
    
      /**
       * Registers a menu to be scrolled with the default number of items to
       * display at a time and the specified scrolling interval.
       *
       * @param menu the menu
       * @param scrollCount the number of items to display at a time
       * @return the MenuScroller
       * @throws IllegalArgumentException if scrollCount is 0 or negative
       */
      public static MenuScroller setScrollerFor(JMenu menu, int scrollCount) {
        return new MenuScroller(menu, scrollCount);
      }
    
      /**
       * Registers a popup menu to be scrolled with the default number of items to
       * display at a time and the specified scrolling interval.
       *
       * @param menu the popup menu
       * @param scrollCount the number of items to display at a time
       * @return the MenuScroller
       * @throws IllegalArgumentException if scrollCount is 0 or negative
       */
      public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount) {
        return new MenuScroller(menu, scrollCount);
      }
    
      /**
       * Registers a menu to be scrolled, with the specified number of items to
       * display at a time and the specified scrolling interval.
       *
       * @param menu the menu
       * @param scrollCount the number of items to be displayed at a time
       * @param interval the scroll interval, in milliseconds
       * @return the MenuScroller
       * @throws IllegalArgumentException if scrollCount or interval is 0 or negative
       */
      public static MenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval) {
        return new MenuScroller(menu, scrollCount, interval);
      }
    
      /**
       * Registers a popup menu to be scrolled, with the specified number of items to
       * display at a time and the specified scrolling interval.
       *
       * @param menu the popup menu
       * @param scrollCount the number of items to be displayed at a time
       * @param interval the scroll interval, in milliseconds
       * @return the MenuScroller
       * @throws IllegalArgumentException if scrollCount or interval is 0 or negative
       */
      public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval) {
        return new MenuScroller(menu, scrollCount, interval);
      }
    
      /**
       * Registers a menu to be scrolled, with the specified number of items
       * to display in the scrolling region, the specified scrolling interval,
       * and the specified numbers of items fixed at the top and bottom of the
       * menu.
       *
       * @param menu the menu
       * @param scrollCount the number of items to display in the scrolling portion
       * @param interval the scroll interval, in milliseconds
       * @param topFixedCount the number of items to fix at the top.  May be 0.
       * @param bottomFixedCount the number of items to fix at the bottom. May be 0
       * @throws IllegalArgumentException if scrollCount or interval is 0 or
       * negative or if topFixedCount or bottomFixedCount is negative
       * @return the MenuScroller
       */
      public static MenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval,
              int topFixedCount, int bottomFixedCount) {
        return new MenuScroller(menu, scrollCount, interval,
                topFixedCount, bottomFixedCount);
      }
    
      /**
       * Registers a popup menu to be scrolled, with the specified number of items
       * to display in the scrolling region, the specified scrolling interval,
       * and the specified numbers of items fixed at the top and bottom of the
       * popup menu.
       *
       * @param menu the popup menu
       * @param scrollCount the number of items to display in the scrolling portion
       * @param interval the scroll interval, in milliseconds
       * @param topFixedCount the number of items to fix at the top.  May be 0
       * @param bottomFixedCount the number of items to fix at the bottom.  May be 0
       * @throws IllegalArgumentException if scrollCount or interval is 0 or
       * negative or if topFixedCount or bottomFixedCount is negative
       * @return the MenuScroller
       */
      public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval,
              int topFixedCount, int bottomFixedCount) {
        return new MenuScroller(menu, scrollCount, interval,
                topFixedCount, bottomFixedCount);
      }
    
      /**
       * Constructs a <code>MenuScroller</code> that scrolls a menu with the
       * default number of items to display at a time, and default scrolling
       * interval.
       *
       * @param menu the menu
       */
      public MenuScroller(JMenu menu) {
        this(menu, 15);
      }
    
      /**
       * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
       * default number of items to display at a time, and default scrolling
       * interval.
       *
       * @param menu the popup menu
       */
      public MenuScroller(JPopupMenu menu) {
        this(menu, 15);
      }
    
      /**
       * Constructs a <code>MenuScroller</code> that scrolls a menu with the
       * specified number of items to display at a time, and default scrolling
       * interval.
       *
       * @param menu the menu
       * @param scrollCount the number of items to display at a time
       * @throws IllegalArgumentException if scrollCount is 0 or negative
       */
      public MenuScroller(JMenu menu, int scrollCount) {
        this(menu, scrollCount, 150);
      }
    
      /**
       * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
       * specified number of items to display at a time, and default scrolling
       * interval.
       *
       * @param menu the popup menu
       * @param scrollCount the number of items to display at a time
       * @throws IllegalArgumentException if scrollCount is 0 or negative
       */
      public MenuScroller(JPopupMenu menu, int scrollCount) {
        this(menu, scrollCount, 150);
      }
    
      /**
       * Constructs a <code>MenuScroller</code> that scrolls a menu with the
       * specified number of items to display at a time, and specified scrolling
       * interval.
       *
       * @param menu the menu
       * @param scrollCount the number of items to display at a time
       * @param interval the scroll interval, in milliseconds
       * @throws IllegalArgumentException if scrollCount or interval is 0 or negative
       */
      public MenuScroller(JMenu menu, int scrollCount, int interval) {
        this(menu, scrollCount, interval, 0, 0);
      }
    
      /**
       * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
       * specified number of items to display at a time, and specified scrolling
       * interval.
       *
       * @param menu the popup menu
       * @param scrollCount the number of items to display at a time
       * @param interval the scroll interval, in milliseconds
       * @throws IllegalArgumentException if scrollCount or interval is 0 or negative
       */
      public MenuScroller(JPopupMenu menu, int scrollCount, int interval) {
        this(menu, scrollCount, interval, 0, 0);
      }
    
      /**
       * Constructs a <code>MenuScroller</code> that scrolls a menu with the
       * specified number of items to display in the scrolling region, the
       * specified scrolling interval, and the specified numbers of items fixed at
       * the top and bottom of the menu.
       *
       * @param menu the menu
       * @param scrollCount the number of items to display in the scrolling portion
       * @param interval the scroll interval, in milliseconds
       * @param topFixedCount the number of items to fix at the top.  May be 0
       * @param bottomFixedCount the number of items to fix at the bottom.  May be 0
       * @throws IllegalArgumentException if scrollCount or interval is 0 or
       * negative or if topFixedCount or bottomFixedCount is negative
       */
      public MenuScroller(JMenu menu, int scrollCount, int interval,
              int topFixedCount, int bottomFixedCount) {
        this(menu.getPopupMenu(), scrollCount, interval, topFixedCount, bottomFixedCount);
      }
    
      /**
       * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
       * specified number of items to display in the scrolling region, the
       * specified scrolling interval, and the specified numbers of items fixed at
       * the top and bottom of the popup menu.
       *
       * @param menu the popup menu
       * @param scrollCount the number of items to display in the scrolling portion
       * @param interval the scroll interval, in milliseconds
       * @param topFixedCount the number of items to fix at the top.  May be 0
       * @param bottomFixedCount the number of items to fix at the bottom.  May be 0
       * @throws IllegalArgumentException if scrollCount or interval is 0 or
       * negative or if topFixedCount or bottomFixedCount is negative
       */
      public MenuScroller(JPopupMenu menu, int scrollCount, int interval,
              int topFixedCount, int bottomFixedCount) {
        if (scrollCount <= 0 || interval <= 0) {
          throw new IllegalArgumentException("scrollCount and interval must be greater than 0");
        }
        if (topFixedCount < 0 || bottomFixedCount < 0) {
          throw new IllegalArgumentException("topFixedCount and bottomFixedCount cannot be negative");
        }
    
        upItem = new MenuScrollItem(MenuIcon.UP, -1);
        downItem = new MenuScrollItem(MenuIcon.DOWN, +1);
        setScrollCount(scrollCount);
        setInterval(interval);
        setTopFixedCount(topFixedCount);
        setBottomFixedCount(bottomFixedCount);
    
        this.menu = menu;
        menu.addPopupMenuListener(menuListener);
        menu.addMouseWheelListener(new MouseScrollListener());
      }
    
      /**
       * Returns the scroll interval in milliseconds
       *
       * @return the scroll interval in milliseconds
       */
      public int getInterval() {
        return interval;
      }
    
      /**
       * Sets the scroll interval in milliseconds
       *
       * @param interval the scroll interval in milliseconds
       * @throws IllegalArgumentException if interval is 0 or negative
       */
      public void setInterval(int interval) {
        if (interval <= 0) {
          throw new IllegalArgumentException("interval must be greater than 0");
        }
        upItem.setInterval(interval);
        downItem.setInterval(interval);
        this.interval = interval;
      }
    
      /**
       * Returns the number of items in the scrolling portion of the menu.
       *
       * @return the number of items to display at a time
       */
      public int getscrollCount() {
        return scrollCount;
      }
    
      /**
       * Sets the number of items in the scrolling portion of the menu.
       *
       * @param scrollCount the number of items to display at a time
       * @throws IllegalArgumentException if scrollCount is 0 or negative
       */
      public void setScrollCount(int scrollCount) {
        if (scrollCount <= 0) {
          throw new IllegalArgumentException("scrollCount must be greater than 0");
        }
        this.scrollCount = scrollCount;
        MenuSelectionManager.defaultManager().clearSelectedPath();
      }
    
      /**
       * Returns the number of items fixed at the top of the menu or popup menu.
       *
       * @return the number of items
       */
      public int getTopFixedCount() {
        return topFixedCount;
      }
    
      /**
       * Sets the number of items to fix at the top of the menu or popup menu.
       *
       * @param topFixedCount the number of items
       */
      public void setTopFixedCount(int topFixedCount) {
        if (firstIndex <= topFixedCount) {
          firstIndex = topFixedCount;
        } else {
          firstIndex += (topFixedCount - this.topFixedCount);
        }
        this.topFixedCount = topFixedCount;
      }
    
      /**
       * Returns the number of items fixed at the bottom of the menu or popup menu.
       *
       * @return the number of items
       */
      public int getBottomFixedCount() {
        return bottomFixedCount;
      }
    
      /**
       * Sets the number of items to fix at the bottom of the menu or popup menu.
       *
       * @param bottomFixedCount the number of items
       */
      public void setBottomFixedCount(int bottomFixedCount) {
        this.bottomFixedCount = bottomFixedCount;
      }
    
      /**
       * Scrolls the specified item into view each time the menu is opened.  Call this method with
       * <code>null</code> to restore the default behavior, which is to show the menu as it last
       * appeared.
       *
       * @param item the item to keep visible
       * @see #keepVisible(int)
       */
      public void keepVisible(JMenuItem item) {
        if (item == null) {
          keepVisibleIndex = -1;
        } else {
          int index = menu.getComponentIndex(item);
          keepVisibleIndex = index;
        }
      }
    
      /**
       * Scrolls the item at the specified index into view each time the menu is opened.  Call this
       * method with <code>-1</code> to restore the default behavior, which is to show the menu as
       * it last appeared.
       *
       * @param index the index of the item to keep visible
       * @see #keepVisible(javax.swing.JMenuItem)
       */
      public void keepVisible(int index) {
        keepVisibleIndex = index;
      }
    
      /**
       * Removes this MenuScroller from the associated menu and restores the
       * default behavior of the menu.
       */
      public void dispose() {
        if (menu != null) {
          menu.removePopupMenuListener(menuListener);
          menu = null;
        }
      }
    
      /**
       * Ensures that the <code>dispose</code> method of this MenuScroller is
       * called when there are no more refrences to it.
       *
       * @exception  Throwable if an error occurs.
       * @see MenuScroller#dispose()
       */
      @Override
      public void finalize() throws Throwable {
        dispose();
      }
      
    
      private void refreshMenu() {
        if (menuItems != null && menuItems.length > 0) {
          firstIndex = Math.max(topFixedCount, firstIndex);
          firstIndex = Math.min(menuItems.length - bottomFixedCount - scrollCount, firstIndex);
    
          upItem.setEnabled(firstIndex > topFixedCount);
          downItem.setEnabled(firstIndex + scrollCount < menuItems.length - bottomFixedCount);
    
          menu.removeAll();
          for (int i = 0; i < topFixedCount; i++) {
            menu.add(menuItems[i]);
          }
          if (topFixedCount > 0) {
            menu.addSeparator();
          }
    
          menu.add(upItem);
          for (int i = firstIndex; i < scrollCount + firstIndex; i++) {
            menu.add(menuItems[i]);
          }
          menu.add(downItem);
    
          if (bottomFixedCount > 0) {
            menu.addSeparator();
          }
          for (int i = menuItems.length - bottomFixedCount; i < menuItems.length; i++) {
            menu.add(menuItems[i]);
          }
    
          JComponent parent = (JComponent) upItem.getParent();
    
          int preferredWidth = 0;
          for (Component item : menuItems) {
            preferredWidth = Math.max(preferredWidth, item.getPreferredSize().width);
          }
          menu.setPreferredSize(new Dimension(preferredWidth, menu.getPreferredSize().height));
    
          parent.revalidate();
          parent.repaint();
        }
    
      }
    
      private class MenuScrollListener implements PopupMenuListener {
    
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
          setMenuItems();
        }
    
        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
          restoreMenuItems();
        }
    
        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
          restoreMenuItems();
        }
    
        
    
        private void setMenuItems() {
          menuItems = menu.getComponents();
          if (keepVisibleIndex >= topFixedCount
                  && keepVisibleIndex <= menuItems.length - bottomFixedCount
                  && (keepVisibleIndex > firstIndex + scrollCount
                  || keepVisibleIndex < firstIndex)) {
            firstIndex = Math.min(firstIndex, keepVisibleIndex);
            firstIndex = Math.max(firstIndex, keepVisibleIndex - scrollCount + 1);
          }
          if (menuItems.length > topFixedCount + scrollCount + bottomFixedCount) {
            refreshMenu();
          }
        }
         
    
        private void restoreMenuItems() {
          menu.removeAll();
          for (Component component : menuItems) {
            menu.add(component);
          }
        }
      }
    
      private class MenuScrollTimer extends Timer {
    
        public MenuScrollTimer(final int increment, int interval) {
          super(interval, new ActionListener() {
    
            @Override
            public void actionPerformed(ActionEvent e) {
              firstIndex += increment;
              refreshMenu();
            }
          });
        }
    
        
       
      }
    
      private class MenuScrollItem extends JMenuItem
              implements ChangeListener {
    
        private MenuScrollTimer timer;
    
        public MenuScrollItem(MenuIcon icon, int increment) {
          setIcon(icon);
          setDisabledIcon(icon);
          timer = new MenuScrollTimer(increment, interval);
          addChangeListener(this);
        }
    
        public void setInterval(int interval) {
          timer.setDelay(interval);
        }
    
        @Override
        public void stateChanged(ChangeEvent e) {
          if (isArmed() && !timer.isRunning()) {
            timer.start();
          }
          if (!isArmed() && timer.isRunning()) {
            timer.stop();
          }
        }
        
      }
      
    
      private static enum MenuIcon implements Icon {
    
        UP(9, 1, 9),
        DOWN(1, 9, 1);
        final int[] xPoints = {1, 5, 9};
        final int[] yPoints;
    
        MenuIcon(int... yPoints) {
          this.yPoints = yPoints;
        }
    
        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
          Dimension size = c.getSize();
          Graphics g2 = g.create(size.width / 2 - 5, size.height / 2 - 5, 10, 10);
          g2.setColor(Color.GRAY);
          g2.drawPolygon(xPoints, yPoints, 3);
          if (c.isEnabled()) {
            g2.setColor(Color.BLACK);
            g2.fillPolygon(xPoints, yPoints, 3);
          }
          g2.dispose();
        }
    
        @Override
        public int getIconWidth() {
          return 0;
        }
    
        @Override
        public int getIconHeight() {
          return 10;
        }
      }
        private class MouseScrollListener implements MouseWheelListener {
            public void mouseWheelMoved(MouseWheelEvent mwe){
                firstIndex += mwe.getWheelRotation();
                refreshMenu();
                mwe.consume(); // (Comment 16, Huw)
            }
        }
    }


    Java Code:
    package fontchooser2;
    
    import javax.swing.JFrame;
    import javax.swing.JMenuBar;
    
    /**
     *
     * @author willem
     */
    public class Main {
    
        /**
         * tester  class
         */
        public static void main(String[] args) {
            JFrame frame = new JFrame("Font Menu Test");
    
            MenuFontMenu fm = new MenuFontMenu(frame);
            JMenuBar mb = new JMenuBar();
            mb.add(fm.buildFontMenu());
            frame.setJMenuBar(mb);
    
            frame.setSize(300, 300);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
    }

  3. #3
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,038
    Rep Power
    8

    Default Re: a font chooser example

    There are four "global" variables of importance at the basic GUI of my text writer application. These variables should be available at several classes and that is quit a thing to do. The variables are:
    -currentFile (the file that is currently open),
    -currentFont (the current font family),
    -currentStyle,
    -currentSize and
    -currentColor (color of the font).

    What is the best why to deal with these variables? Should I construct an interface and make them available in a event string? Like this:

    currentFont,currentStyle,currentSize,currentColor, currentFiles (the last as a arraylist of strings).

    Where one can learn these kind of things?

    Any book or manual present?

    The currentFont is set at the MenuFontMenu class and the other three are set at the MeneFontMenu2 class which is created at MenuFontMenu class. At the MenuFontMenu class I make them all available like this:

    Java Code:
    public String getCurrentFont()    {
             return currentFont;
         }
         public int getCurrentSize()    {
             return fontMenu2.getCurrentSize();
         }
    
         public int getCurrentStyle()    {
             return fontMenu2.getCurrentStyle();
         }
    
         public Color getCurrentColor()    {
             return fontMenu2.getCurrentColor();
         }
    
    
         //relevant setters getters for the actions
         public ColorAction[] getColorActions()  { 
             return fontMenu2.getColorActions();
         }
    
          public StyleAction[] getStyleAction() { 
             return fontMenu2.getStyleAction();
         }
    
         public SizeAction[] getSizeAction() {
             return fontMenu2.getSizeAction();
         }
    
         public String[] getSizeList() {
             return fontMenu2.getSizeList();
         }




    I improved the MenuFontMenu2 class by splitting out the actions to a single action
    of each font Item (font, style, size and color):







    Java Code:
     public JMenu buildFontMenu2(JMenu jm) {      // the previous font class MenuFontMenu
                                                                           // sets the reference (jm) for
             //the fontstyle menu added                            extending the menu list
             JMenu fontStyle = new JMenu("Font Style");
             Font font;
             Font ft = jm.getFont();
             JRadioButtonMenuItem rbStyle = null;
             ButtonGroup buttongroupStyle = new ButtonGroup();
    
             styleActions = new StyleAction[fontStyleList.length];
    
             for (int i=0; i < fontStyleList.length; i++) { // the style menu  
                styleActions[i] = new
                        StyleAction(fontStyleList[i].getFontStyleKey(),
                                    fontStyleList[i].getFontStyleIcon(),
                                    fontStyleList[i].getFontStyleValue());
                font = new Font("" + ft, fontStyleList[i].getFontStyleValue(), 16);
                rbStyle = new JRadioButtonMenuItem(styleActions[i]);
                rbStyle.setFont(font);
                rbStyle.setText("" + fontStyleList[i].getFontStyleKey());
                buttongroupStyle.add(rbStyle);
                fontStyle.add(rbStyle);
             }
    
             jm.add(fontStyle);
    
             //the font size menu added
             JMenu fontSize = new JMenu("Font Size");
             ft = jm.getFont();
             JRadioButtonMenuItem rbSize;
             ButtonGroup buttongroupSize = new ButtonGroup();
    
             sizeActions = new SizeAction[fontSizeList.length];
             for (int i=0; i < fontSizeList.length; i++) { // the font size menu
                sizeActions[i] = new
                        SizeAction(fontSizeList[i],
                        Integer.parseInt(fontSizeList[i]));
                rbSize = new JRadioButtonMenuItem(sizeActions[i]);
                buttongroupSize.add(rbSize);
                fontSize.add(rbSize);
             }
    
             jm.add(fontSize);
    
             //the color menu added
             JMenu fontColor = new JMenu("Font Color");
             ft = jm.getFont();
             JRadioButtonMenuItem rbColor;
             colorActions = new ColorAction[colorMap.size()];
    
             Set entries = colorMap.entrySet();
             Iterator iter = entries.iterator();
             int count = 0;
             ButtonGroup buttongroupColor = new ButtonGroup();
             while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry)iter.next();
                String key = (String) entry.getKey();
                Color value = (Color) entry.getValue();
                colorActions[count] = new ColorAction("", value);
                rbColor = new JRadioButtonMenuItem(colorActions[count]);
                rbColor.setText(key);
                buttongroupColor.add(rbColor);
                fontColor.add(rbColor);
                count++;
              }
    
            jm.add(fontColor);
    
            return jm;
         }
    
        // the acolor actions
         class ColorAction extends AbstractAction {
            ColorAction(String name, Color c) { 
                                                
                color = c;
                putValue(NAME, name);
                putValue(SMALL_ICON, new ColorFillIcon(c, 15, 10, 1));
                putValue(MNEMONIC_KEY, new Integer('N'));
                putValue(SHORT_DESCRIPTION, "Creates whatever");
                putValue(LONG_DESCRIPTION, "Creating whatever...");
    
            }
            // Action to take when this color is selected
            public void actionPerformed(ActionEvent evt) {
                System.out.println("current color: " + color);
            }
        }
    
        //The style actions
        class StyleAction extends AbstractAction {
            String name;
            int value;
            StyleAction(String name, String iconName, int value) {
                this.name = name;
                this.value = value;
                putValue(NAME, "");
                putValue(SMALL_ICON, iconImport.getImageIcon(iconName));
                putValue(MNEMONIC_KEY, new Integer('N'));
                putValue(SHORT_DESCRIPTION, "Creates whatever");
                putValue(LONG_DESCRIPTION, "Creating whatever...");
            }
            public void actionPerformed(ActionEvent evt) {
                currentStyle = value;
                System.out.println("current font style " + name + ": " + value);
            } //actionPerformed
        }
    
        //The size actions
        class SizeAction extends AbstractAction {
            String name;
            SizeAction(String name, int value) {
                this.name = name;
                putValue(NAME, name);
                putValue(SMALL_ICON, null);
                putValue(MNEMONIC_KEY, new Integer('N'));
                putValue(SHORT_DESCRIPTION, "Creates whatever");
                putValue(LONG_DESCRIPTION, "Creating whatever...");
            }
            public void actionPerformed(ActionEvent evt) {
                currentSize = Integer.parseInt(name);
                System.out.println("current font size: "  + currentSize);
            } //actionPerformed
        }

Similar Threads

  1. Replies: 0
    Last Post: 08-18-2010, 10:31 AM
  2. JFile Chooser
    By karno in forum NetBeans
    Replies: 4
    Last Post: 03-17-2010, 12:47 PM
  3. Replies: 5
    Last Post: 04-25-2009, 08:00 PM
  4. Color Chooser Demo
    By Java Tip in forum javax.swing
    Replies: 0
    Last Post: 06-27-2008, 07:48 PM
  5. Using File Chooser
    By shaungoater in forum New To Java
    Replies: 0
    Last Post: 03-20-2008, 12:30 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •