Page 1 of 3 123 LastLast
Results 1 to 20 of 47
Like Tree1Likes

Thread: need help: writing an interface

  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default need help: writing an interface

    I have worked a lot with interfaces, but never wrote one.
    Now is the time I should get into writing one.
    I need some help here, please.

    I got as far as this:

    Java Code:
    package willemwriter;
    
    /**
     *
     * @author willem
     */
    interface FontChange {
        // next should set the variable currentFontFamily of type String
        public void fontFamilyChange(); 
    
        //next should set the variable currentFontStyle of type int
        public void fontStyleChange();
    
        //next should set the variable currentFontSize of type int
        public void fontSizeChange();
    
        //next should set the variable currentFontColor of type Color
        public void fontColorChange();
    
        //next should set the Map shortMenuMap of the type <String,Object> 
        public void ShortFontList();
    }
    All present five variables are created through actions at one single class
    called MenuFontMenu. The are the result of actions related to several menus
    and two toolbars with buttons and combo boxes.
    I might have to work with listeners?
    So how I go from here?

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

    Default Re: need help: writing an interface

    I think the problem I am facing is this. One is very much trained in thinking "clockwise" in Java:
    Diclearing classes and making objects of other classes in classes, all in a one way direction (Top/ Down).
    When one has to think suddenly counter clockwise thinks get confusing, right?
    So now I am looking into some "call back" models like this:

    Java Code:
    interface*Callable**{**
    ****public*void*callBackMethod();**
    }**
    class*Worker**{**
    ****//*Worker*gets*a*handle*to*the*boss*object*via*the*Callable*interface.**
    ****//*There's*no*way*this*worker*class*can*call*any*other*method*other*than**
    ****//*the*one*in*Callable.**
    ****public*void*doSomeWork(Callable*myBoss)* {**
    ********myBoss.callBackMethod();**			//4
    ********//*ERROR!**
    ********//myBoss.directMethod();**
    ****}**
    }**
    class*Boss*implements*Callable**{**
    ****public*Boss() {**
    ********//*Boss*creates*a*worker*object,*and*tells*it*to*do*some*work.**
    ********Worker*w1*=*new*Worker();**			//2
    ********//*Notice,*we're*passing*a*reference*of*the*boss*to*the*worker.**
    ********w1.doSomeWork(this);**			//3
    ****}**
    ****public*void*callBackMethod() {**		//5
    ********System.out.println("What*do*you*want?");**
    ****}**
    ****public*void*directMethod()*{**
    ********System.out.println("I'm*out*for*coffee.");**
    ****}**
    }**
    public*class*CallBack*{**
    ****//*Main*driver.**
    ****public*static*void*main(String[]*args)*{**
    ********Boss*b*=*new*Boss();**			//1
    ********b.directMethod();**				//6
    ****}**
    }**
    and it is starting to become much clearer!

    I remodeled my interface like this :

    Java Code:
    interface FontChangeable {
        // should set the variable currentFontFamily of type String
        public String fontFamilyChange();
        //should set the variable currentFontStyle of type int
        public int fontStyleChange();
        //should set the variable currentFontSize of type int
        public int fontSizeChange();
        //should set the variable currentFontColor of type Color
        public Color fontColorChange();
        //should set the Map shortMenuMap of the type <String,Object>
        public Map<String,Object> ShortFontList();
    }
    and made the MenuFontMenu (implements FontChangeable) class, that makes all these
    variables available, implement the methods like this:

    Java Code:
    public String fontFamilyChange() {
            return currentFont;  
        }
    
        public int fontStyleChange() {
            return currentStyle;
        }
    
        public int fontSizeChange() {
            return currentStyle;
        }
    
        public Color fontColorChange() {
            return currentColor;
        }
    
        public Map<String,Object> ShortFontList() {
            return shortMenuMap;
        }
    So let see what's next?

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

    Default Re: need help: writing an interface

    (Sorry I do not know where these strange stars come from)

  4. #4
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: need help: writing an interface

    Before you go any further, read the link in my sig.
    Get in the habit of using standard Java naming conventions!

  5. #5
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: need help: writing an interface

    Thanks I will

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,023
    Rep Power
    6

    Default Re: need help: writing an interface

    I am not an expert on interface design, but I tend to focus on the what and not the how. When you specify an interface you are expected to specify its behavior. But you should not be specifying the names of the variables to set. Those are mostly irrelevant and should be transparent to the user of the interface. If you specify a method called setColor(Color color), why does it matter if I store that color as foo or someArray[0]?

    In your example your comment says to set a specific map, by name. It would be better, if is required to use a map at all, to specify the map type in the signature. Let the implementer choose the name.

    Regards,
    Jim
    gimbal2 likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,354
    Rep Power
    6

    Default Re: need help: writing an interface

    100% agree with Jim; interfaces define a contract, not a solution. As long as an implementation sticks to defined boundaries and rules regarding functionality and behavior, it shouldn't matter how the implementation is done. And even if it would, adding comments is not going to force anyone to listen to you.

    Quote Originally Posted by willemjav View Post
    Now is the time I should get into writing one.
    Can you explain why? If you provide some background, it might help people to give more direct advice.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  8. #8
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,086
    Rep Power
    4

    Default Re: need help: writing an interface

    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2™ © 2013

  9. #9
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: need help: writing an interface

    I believe I need a so called call-back function to reach a specific class (actually several classes) at my text writer program.
    Here is the situation:

    The base class of the GUI (class Wwframe extends JFrame, coming immediately out of the main method) does three things:
    1) it sets all menus and add them to the frame (each menu in a separate class plus helper classes);
    2) it sets the two toolbars (one single class plus helper classes);
    3) it sets the text canvas (up for discussion later)
    All menus run on Actions and several of them are doubled, as buttons or combo boxes, at the fool bars.

    Here is how that goes into code:

    Java Code:
    TextCanvas textcanvas = new TextCanvas();
            
            // all menu classes
            fileMenu = new MenuFileMenu(textcanvas);
            editMenu = new MenuEditMenu(textcanvas);
            viewMenu = new MenuViewMenu(textcanvas);
            insertMenu = new MenuInsertMenu(textcanvas);
            fontMenu = new MenuFontMenu(textcanvas); // for both font menus
            windowsMenu = new MenuWindowsMenu(textcanvas);
    
            JMenuBar mb = new JMenuBar();
            setJMenuBar(mb);
    
            // the build of each menu
            mb.add(fileMenu.buildFileMenu());
            mb.add(editMenu.buildEditMenu());
            mb.add(viewMenu.buildViewMenu());
            mb.add(insertMenu.buildInsertMenu());
            mb.add(fontMenu.buildFontMenu());
            mb.add(windowsMenu.buildWindowsMenu());
    
    	// the two tool bars in one single class plus helpers
            WriterToolBar toolbar = new WriterToolBar(this);
    
            toolbar.setColorAction(fontMenu.getColorAction());
            toolbar.setStyleAction(fontMenu.getStyleAction());
            toolbar.setSizeAction(fontMenu.getSizeAction());
            toolbar.setSizeList(fontMenu.getSizeList());
         
            toolbar.setOpenAction(fileMenu.getOpenAction());
            toolbar.setSaveAction(fileMenu.getSaveAction());
    
            JPanel toolbarPanel = new JPanel();
            toolbarPanel.setLayout(new GridLayout(2,0));
            toolbarPanel.add(toolbar.BuildToolbar1());
            toolbarPanel.add(toolbar.BuildToolbar2());
    
    
            getContentPane().add(toolbarPanel, BorderLayout.NORTH);
            getContentPane().add(textcanvas, BorderLayout.CENTER);
    When running the program all the above stuff get initiated and rund just fine!

    Now the user starts to interact with the application, selecting files and menus, right!

    Now five issues are important:
    1) the selected file, currentFile;
    2) the selected font family, currentFont;
    3) the selected font style. currentStyle;
    4) the selected font size: currentSize;
    5) the selected font color, currentColor;
    6) a short list of all fonts, Map <String,Object> shortMenuMap.
    (at the MenuFontMenu class the user may select his favorite fonts from all the system fonts (a to long list) and when select, selected fonts, this selected short list will appear: which works great). Important is that this short list should appear (only this short list) at the combo box of the tool bar (you see the problem here).

    So now I will focus on one issue which is characteristic for several more:
    -At the MenuFontMenu class only the font family is subject
    -At the MenuFontMenu2 class the style, size and color of the font are subjects, but this menu gets added to the previous font family menu.

    The shortlist of fonts is constructed at the MenuFontMenu class through Actions (the all-font-list menu turns from menu radio boxes into menu check boxes and the selection of the short list is stored in the map shortMenuMap and the all-font-list gets removed from the menu and the shortlist gets added. All this works!

    The problem is how do I make that shortlist available at the combo box of the toolbar after the user changed it?

    I can (after many trying and thinking) only think of a callback function by using a interface (as well to make the current font variables available).

  10. #10
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: need help: writing an interface

    On more thing and the problem I am struggling with becomes very clear.
    The MenuFontMenu2 also contains the font size menu. The numbers of the pts at that menu are again Actions added
    (actually an array of actions). This font size menu has a brother at the toolbar, where you find a font size combo box.
    When adding the action array to the combo box the toString kicks in and adds a long string as combo item which,
    I believe, presents the action objects (which is not what I want here). So I added a array of String (numbers) instead
    (see above: fontMenu.getSizeList());)

    The issue is, when selected a font family or font size or what ever at the menu, I want this selection also to appear at the
    Toolbar!

  11. #11
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: need help: writing an interface

    This is a good case for the MVC design pattern. The model is the "state" of your program. This would be an object that contains the six things you listed above. The actual UI components are the view. When the model changes, it fires events to listeners that update the view. So, for example, if the selected font family is changed via the menu, the toolbar will receive an event that updates it.

    You could write your own listener interface, but there's already a standard interface for this built into Swing. Here's a good introduction: https://weblogs.java.net/blog/joshy/...il_the_pr.html
    Get in the habit of using standard Java naming conventions!

  12. #12
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: need help: writing an interface

    kjkrum, I have worked with the property listener and I know it is a very powerful one, thanks.
    I am study the code example of the link!

    Another powerful idea might be to keep all information concerning the action within the property of that action.
    You see the Abstract action class has for instance the property of is/setEnabled(). I am not using that property here, though.
    Instead I would like to find the is/setSelected() property which is not present.

    I know how to add properties (Action.putValue(java.lang.String, java.lang.Object))
    But how to "create" one?

    Than I found this http://dev.cs.uni-magdeburg.de/java/...ActionExt.html
    Which I will be studying too!

    AnyWay I forgot about the importance of "Design patterns" --feeling like I am at a circus with too many balls in the ear--
    I should look into this important stuff as well (I remember reading the Thinking Java book and got mad with all
    those banana and grapefruit classes, but maybe have to look into that book again concerning class design, right?)

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,023
    Rep Power
    6

    Default Re: need help: writing an interface

    [QUOTE=willemjav;370031
    I know how to add properties (Action.putValue(java.lang.String, java.lang.Object))
    But how to "create" one?
    [/QUOTE]

    Properties are nothing more that strings which identify certain items (well, properties) of an environment (the scope of which is up to the designer). In fact, they are similar, IMO, to the environment variables of most OS's.

    They are discussed here --> Properties (The Java™ Tutorials > Essential Classes > The Platform Environment)

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  14. #14
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: need help: writing an interface

    Yes I read that stuff before, but let see if I understand it well.
    When asking isEnabled() you´ll get a boolean property of e.g. an action (of a class that extends AbstractAction).
    In the same way setEnabled() sets the property, right?
    This setter and getter works the class mentioned.

    But when I try to do the same with is/setSelected() it will not work because these properties are not installed?
    or how do I have to see this?

  15. #15
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: need help: writing an interface

    I still have to study this interesting link which will give a clue of all this
    GrepCode: org.jdesktop.swingx.action.AbstractActionExt (.java) - Class - Source Code View

  16. #16
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: need help: writing an interface

    Maybe this will help.

    Java Code:
    public class MyModel {
       public static final string PROP_VALUE = "value"; // could be any string as long as it is unique
       private final PropertyChangeSupport pcs;
       private boolean value;
    
       public MyModel(PropertyChangeSupport pcs) {
          this.pcs = pcs;
       }
    
       public void setValue(boolean value) {
          if(this.value != value) {
             this.value = value;
             pcs.firePropertyChange(PROP_VALUE, !value, value);
          }
       }
    
       public void getValue() {
          return value;
       }
    
    }
    Now components that want to know when the value changes can register to receive MyModel.PROP_VALUE on the same PropertyChangeSupport object you passed to the model.
    Last edited by kjkrum; 01-30-2014 at 06:25 PM.
    Get in the habit of using standard Java naming conventions!

  17. #17
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: need help: writing an interface

    At the Baseclass: I create object of the Aclass.
    The Aclass creates an array list called fontlist.
    The list is created by the user so not available when initiating the Aclass!

    -Aclass a = new Aclass();
    -ArrayList fontList;

    -Bclass b = new Bclass();

    -At the Baseclass I can say
    a.getFontList();

    1) When the list becomes available I at the Aclass I trigger a
    this.firePropertyChange("FONTLIST",false,t rue);
    at the Aclass

    2) now I need to code a listener at the Bclass like this:

    Java Code:
    addPropertyChangeListener("FONTLIST",
                                                new PropertyChangeListener() {
                          public void propertyChange(PropertyChangeEvent event) {
                          // this will receive the event from the Aclass?
                    }
          });
    Where do I need to add the listener to?

    Is there still something missing?

  18. #18
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: need help: writing an interface

    the lines crossed, I am looking to your stuff now!

  19. #19
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,354
    Rep Power
    6

    Default Re: need help: writing an interface

    Quote Originally Posted by willemjav View Post
    the lines crossed, I am looking to your stuff now!
    You dirty man!
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  20. #20
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: need help: writing an interface

    BINGO

    Any comments please:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeSupport;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    /**
     *
     * @author willem
     */
    public class ClassA {
        PropertyChangeSupport changeSupport;
    
         ClassA() {
             
             ClassB b = new ClassB();
             
             JFrame frame = new JFrame();
             changeSupport = b. getChangeSupport();
    
             Container contentPane = frame.getContentPane();
             contentPane.add(b.createButton(), BorderLayout.NORTH);
             contentPane.add(createInfoPanel(), BorderLayout.SOUTH);
             frame.pack();
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
         }
    
         public JPanel createInfoPanel()  {
            JPanel infoPanel = new JPanel();
            final JLabel infoLabel = new JLabel("info");
            infoPanel.add(infoLabel);
    
            changeSupport.addPropertyChangeListener("Shortlist",
                                                new PropertyChangeListener() {
                    public void propertyChange(PropertyChangeEvent event) {
                        infoLabel.setText("BINGO");
                    }
            });
    
            return infoPanel;
         }
    
         public static void main(String arg[]) {
             new ClassA();
         }
    }

    Java Code:
    package callback;
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeSupport;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    
    /**
     *
     * @author willem
     */
    public class ClassB extends JPanel{
        PropertyChangeSupport changeSupport;
    
        public ClassB() {
            changeSupport = new PropertyChangeSupport(this);
        }
        
        public PropertyChangeSupport getChangeSupport() {
            return changeSupport;
        }
        
        public JPanel createButton()  {
            
            JPanel panel = new JPanel();
            JButton button = new JButton("Action");
             button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    System.out.println("action pushed");
                    changeSupport.firePropertyChange("Shortlist",false,true);
                }
             });
             panel.add(button);
             return panel;
        } 
    
    }

Page 1 of 3 123 LastLast

Similar Threads

  1. Replies: 1
    Last Post: 07-08-2012, 06:23 PM
  2. writing a program to interface with other programs
    By gib65 in forum Advanced Java
    Replies: 4
    Last Post: 11-04-2011, 11:09 PM
  3. Replies: 1
    Last Post: 02-27-2010, 02:29 AM

Posting Permissions

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