MenuItem ActionListener bug (MVC pattern)

Hello. I'm implementing a book store system using the MVC pattern, but due to the fact that the method actionPerformed() is in class libraryController it doesn't work (and I need it in this class due to the MVC pattern). Can anyone help me? Thanks.
   class libraryView extends JFrame{
  JMenuItem addBook = new JMenuItem("Add Book");
  JMenuItem deleteBook = new JMenuItem("Delete Book");
   JMenuItem modifyByTitle = new JMenuItem("Modify by Title");
   JMenuItem modifyByAuthor = new JMenuItem("Modify by Author");
   JMenuItem searchByTitle = new JMenuItem("Search by Title");
    JMenuItem searchByAuthor = new JMenuItem("Search by Author");
    JMenuItem searchByID = new JMenuItem("Search by ID");
    JMenuItem bookListing = new JMenuItem("Book Listing");
   public JPanel createContentPane()
        JPanel totalGUI = new JPanel();
        totalGUI.setBackground(Color.white);
        totalGUI.setMinimumSize(new Dimension(300, 200));
        totalGUI.setPreferredSize(new Dimension(500, 500));
        totalGUI.setMaximumSize(new Dimension(300, 200));
        totalGUI.setOpaque(true);
        return totalGUI;
    public JMenuBar createMenuBar(){
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("Options");
        menuBar.add(menu);
        menuBar.setBackground(Color.pink);
        addBook.setFont(new Font("Helvetica",Font.PLAIN,13));
        menu.add(addBook);
        deleteBook.setFont(new Font("Microsoft Sans Serif",Font.PLAIN,13));
        menu.add(deleteBook);
       JMenu modifyBook = new JMenu("Modify Book");
        modifyBook.setFont(new Font("Helvetica",Font.PLAIN,13));
        menu.add(modifyBook);
        modifyByTitle.setFont(new Font("Helvetica",Font.PLAIN,13));
        modifyBook.add(modifyByTitle);
        modifyByAuthor.setFont(new Font("Helvetica",Font.PLAIN,13));
        modifyBook.add(modifyByAuthor);
        JMenu searchBook = new JMenu("Search Book");
        searchBook.setFont(new Font("Helvetica",Font.PLAIN,13));
        menu.add(searchBook);
        searchByTitle.setFont(new Font("Helvetica",Font.PLAIN,13));
        searchBook.add(searchByTitle);
        searchByAuthor.setFont(new Font("Helvetica",Font.PLAIN,13));
        searchBook.add(searchByAuthor);
        searchByID.setFont(new Font("Helvetica",Font.PLAIN,13));
        searchBook.add(searchByID);
        bookListing.setFont(new Font("Helvetica",Font.PLAIN,13));
        menu.add(bookListing);
        return menuBar;
    private static void createAndShowGUI(){
        //Create and set up the window.
        // JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JMenuBar [=]");
        //Create and set up the content pane.
        libraryView libr_obj = new libraryView();
        frame.setContentPane(libr_obj.createContentPane());
        // We now also set the MenuBar of the Frame to our MenuBar
        frame.setJMenuBar(libr_obj.createMenuBar());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
   public void init_view(){
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
    void MenuActionListeners(ActionListener al) {
        addBook.setActionCommand("addBook");
        addBook.addActionListener(al);
        deleteBook.setActionCommand("deleteBook");
        deleteBook.addActionListener(al);
        modifyByTitle.setActionCommand("modifyByTitle");
        modifyByTitle.addActionListener(al);
        modifyByAuthor.setActionCommand("modifyByAuthor");
        modifyByAuthor.addActionListener(al);
        searchByTitle.setActionCommand("searchByTitle");
        searchByTitle.addActionListener(al);
        searchByAuthor.setActionCommand("searchByAuthor");
        searchByAuthor.addActionListener(al);
        searchByID.setActionCommand("searchByID");
        searchByID.addActionListener(al);
        bookListing.setActionCommand("bookListing");
        bookListing.addActionListener(al);
class libraryController implements ActionListener{
     libraryModel model;
     libraryView view;
   public libraryController (libraryModel model, libraryView view) {
        this.model = model;
        this.view  = view;
        this.view.init_view();
        view.MenuActionListeners(this);
   public void actionPerformed(ActionEvent ae)
    String action_com = ae.getActionCommand();
        if (action_com.equals("addBook"))
          System.out.println("add Book");
}

Thanks. I think you were right with the new object created, but I still have the problem, although I add the menu bar directly to the frame. Could you provide me a good link or smtg cause I really can't figure it out how to do it. Thank you.
* To change this template, choose Tools | Templates
* and open the template in the editor.
package librabrymanagementf;
import java.awt.event.ActionEvent;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
public class Main {
    public static void main(String[] args) {
              // Creates a model of the system logic.
        libraryModel model = new libraryModel();
        // Creaties a view for the system logic.
        libraryView view = new libraryView();
        // Creates a controller that links the two.
        libraryController controller = new libraryController(model, view);
  class libraryModel{
  class libraryView extends JFrame{
    JFrame frame = new JFrame("[=] JMenuBar [=]");
    JMenuItem addBook = new JMenuItem("Add Book");
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("Options");
    public libraryView()
    frame.setSize(400,400);
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      menuBar.add(menu);
      menu.add(addBook);
      menu.add(deleteBook);
      frame.setJMenuBar(menuBar);
    public void MenuActionListeners(ActionListener al) {
        addBook.setActionCommand("addBook");
        addBook.addActionListener(al);
class libraryController implements ActionListener{
     libraryModel model;
     libraryView view;
   public libraryController (libraryModel model, libraryView view) {
        this.model = model;
        this.view  = view;
        view.MenuActionListeners(this);
   public void actionPerformed(ActionEvent ae)
    String action_com = ae.getActionCommand();
        if (action_com.equals("addBook"))
          System.out.println("oki");
   

Similar Messages

  • What is your strategy for form validation when using MVC pattern?

    This is more of a general discussion topic and will not necessarily have a correct answer. I'm using some of the Flex validator components in order to do form validation, but it seems I'm always coming back to the same issue, which is that in the world of Flex, validation needs to be put in the view components since in order to show error messages you need to set the source property of the validator to an instance of a view component. This again in my case seems to lead to me duplicating the code for setting up my Validators into several views. But, in terms of the MVC pattern, I always thought that data validation should happen in the model, since whether or not a piece of data is valid might be depending on business rules, which again should be stored in the model. Also, this way you'd only need to write the validation rules once for all fields that contain the same type of information in your application.
    So my question is, what strategies do you use when validating data and using an MVC framework? Do you create all the validators in the views and just duplicate the validator if the exact same rules are needed in some other view, or do you store the validators in the model and somehow reference them from the views, changing the source properties as needed? Or do you use some completely different strategy for validating forms and showing error messages to the user?

    Thanks for your answer, JoshBeall. Just to clarify, you would basically create a subclass of e.g. TextInput and add the validation rules to that? Then you'd use your subclass when you need a textinput with validation?
    Anyway, I ended up building sort of my own validation framework. Because the other issue I had with the standard validation was that it relies on inheritance instead of composition. Say I needed a TextInput to both check that it doesn't contain an empty string or just space characters, is between 4 and 100 characters long, and follows a certain pattern (e.g. allows only alphanumerical characters). With the Flex built in validators I would have to create a subclass or my own validator in order to meet all the requirements and if at some point I need another configuration (say just a length and pattern restriction) I would have to create another subclass which duplicates most of the rules, or I would have to build a lot of flags and conditional statements into that one subclass. With the framework I created I can just string together different rules using composition, and the filter classes themselves can be kept very simple since they only need to handle a single condition (check the string length for instance). E.g. below is the rule for my username:
    library["user_name"] = new EmptyStringFilter( new StringLengthFilter(4,255, new RegExpFilter(/^[a-z0-9\-@\._]+$/i) ) );
    <code>library</code> is a Dictionary that contains all my validation rules, and which resides in the model in a ValidationManager class. The framework calls a method <code>validate</code> on the stored filter references which goes through all the filters, the first filter to fail returns an error message and the validation fails:
    (library["user_name"] as IValidationFilter).validate("testuser");
    I only need to setup the rule once for each property I want to validate, regardless where in the app the validation needs to happen. The biggest plus of course that I can be sure the same rules are applied every time I need to validate e.g. a username.
    The second part of the framework basically relies on Chris Callendar's great ErrorTipManager class and a custom subclass of spark.components.Panel (in my case it seemed like the reasonable place to put the code needed, although perhaps extending Form would be even better). ErrorTipManager allows you to force open a error tooltip on a target component easily. The subclass I've created basically allows me to just extend the class whenever I need a form and pass in an array of inputs that I want to validate in the creationComplete handler:
    validatableInputs = [{source:productName, validateAs:"product_name"},
                         {source:unitWeight, validateAs:"unit_weight", dataField:"value"},
                   {source:unitsPerBox, validateAs:"units_per_box", dataField:"value"},
                        {source:producer, validateAs:"producer"}];
    The final step is to add a focusOut handler on the inputs that I want to validate if I want the validation to happen right away. The handler just calls a validateForm method, which in turn iterates through each of the inputs in the validatableInputs array, passing a reference of the input to a suitable validation rule in the model (a reference to the model has been injected into the view for this).
    Having written this down I could probably improve the View side of things a bit, remove the dependency on the Panel component and make the API easier (have the framework wire up more of the boilerplate like adding listeners etc). But for now the code does what it needs to.

  • Can i use Custom Tags for Database retrieval (as per MVC pattern)?

    In our project we are dealing with database, and i've used the Cutom Tags for database retrieval (as per the Article from Mr Faisal Khan) and it is working fine. But i have a doubt if it affects the performance in any way . I wanted to know if its recommendable to use Custom Tags for the DB retrieval as per MVC Pattern or shall i create a intermediate bean and then call the bean in custom tag.
    Thanks
    Prakash

    Putting database code in your JSPs certainly couples your view to the database. That's usually not good.
    If it's a simple app, it might be justified.
    When you start having lots of pages and complex business logic it becomes less attractive. - MOD

  • Protecting Presentation JSP in a MVC Pattern

    why should I use "login-config" type authentication to protect my presentation JSP used in an MVC pattern from direct access, when I can protect it simply by placing it in my WEB-INF?

    Authentication is not just to protect presentation layer but any resource served by the application server.

  • MVC pattern in flash builder

    I am trying to figure out the MVC patter in flash builder. I understand we can seperate view and controller by building custom components as view and populate them in the controller file. However, I don't know how to apply the Model login in flash builder. Do i create a Model folder and file and using that file to receive data?
    For example:
    Main controller:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                                     xmlns:s="library://ns.adobe.com/flex/spark"
                                     xmlns:mx="library://ns.adobe.com/flex/mx"
                                     minWidth="955" minHeight="600"
                                     xmlns:components="components.*">
              <fx:Declarations>
                        <!-- Place non-visual elements (e.g., services, value objects) here -->
                        <s:HTTPService url="test.come" id="testData" result="testData_resultHandler(event)"/>  //Data here
              </fx:Declarations>
              <fx:Script>
                        <![CDATA[
                                  import mx.collections.ArrayCollection;
                                  import mx.rpc.events.ResultEvent;
                                  public var testData:ArrayCollection;
                                  protected function testData_resultHandler(event:ResultEvent):void
                                            testData=event.result.something...   //How to seperate the Data with the main controller?????
                        ]]>
              </fx:Script>
    //view
              <components:videoList />
         <components:videoList2 />
         <components:videoList3 />
    </s:Application>
    I appreciate any replies. Thanks a lot.

    The usual pattern in flex is to have an mxml component 'the view', an actionscript class (the controller), and some additional actionscript classes that represent the data objects (the model). Your 'main' application class is responsible for creating a new instance of the controller, usually as response to the creationComplete event. The controller then initiallizes/retrieves the 'Model' objects and passes them back to the view which binds them to the appropriate fields. So at the bare minimum for an MVC project your are going to have Main.mxml, MainController.as, and Model.as.
    This is not the most elegant solution since it tends to create tight coupling between the controller and the view. If you want to use the MVC pattern on any project that involves more than 3 or 4 simple views you will probably want to look into a custom MVC framework like Cairingorm or the Tide framework from GraniteDS. Make sure you have a solid understanding of the basics first though. 

  • Java server faces mvc pattern

    Well i dont know any knowledge of java servr faces.Dows java Server faces encapsulate mvc pattern like struts other then html tag library.
    Thanks.

    JSF only addresses the "user interface" framework portion of a web application. You can perhaps think of it as standardizing the "V" in MVC (I don't know if this is quite right, is it so Craig?). We wish that there will be another JSR in the future that standardizes rest of the "C" of the MVC.
    -Mete

  • How to apply mvc pattern  to mastermind game coding?

    Hello,
    I am trying to create the mastermind board. i want to know how to apply the MVC pattern to the design
    View -- creating the board
    Model --??
    Controller --??
    I am not able to understand what should be in the model and what shud be in the controller.
    Can anybody help
    Thanks,
    Manju

    * Model - The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model.
    * View -The view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented. It is the view's responsibility to maintain consistency in its presentation when the model changes. This can be achieved by using a push model, where the view registers itself with the model for change notifications, or a pull model, where the view is responsible for calling the model when it needs to retrieve the most current data.
    * Controller - The controller translates interactions with the view into actions to be performed by the model. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in a Web application, they appear as GET and POST HTTP requests. The actions performed by the model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view.
    http://java.sun.com/blueprints/patterns/MVC-detailed.html

  • Observer, MVC pattern

    Hi!
    I am trying to learn about the Observer, MVC pattern.
    The problem is that I cant find any good tutorial... Does anyone know any?

    Hi!
    Sorry for the delay, I have been away!
    I hear what you are saying. Can you then recommend me some Observer guide?
    Can you please give me some tips on how I should design the program.
    This is the design problem I have:
    In the program there are about 4 different components where each component is well suited for the MVC-pattern.
    These for components depend on each other. So for example if the components are A, B, C and D, D can depend on A, B and C. But B only depends on A and B. "depend" may be blurry. In the first case were D depended on A, B and C. That means that when something happens in A, B or C. They will have to update/call a method or something like that in D.

  • Design dialog program using the MVC pattern

    Hi,
    I have to design a dialog program using the MVC pattern , with all the controllers lying inside function modules.
    I have searched out on net and could find out that BSP applications are designed using the MVC concept.Please suggest how can the dialog program be designed using MVC pattern.

    I'm currently developing a classic Dynpro dialog program.  I have a module pool, with screens.  I've tightly coupled the module pool with a controller class.  Anything that happens in the module pool, is handled by the controller class. All the logic of screen handling is done by the controller class.
    What remains in the module pool is the capturing of the okcode. the next screen to go to (if applicable), the setting of field attributes.  But the okcode is sent straight to the controller for processing, and the screen/field information is also held in the controller.
    I've also rewritten the auto-generated tab handling code, so the logic is done via a class. 
    So, it is possible - just aim to have as LITTLE as possible in the module pool or function group.
    The model, of course, is in a separate class.

  • ActionListener demonstrate Observer Pattern?

    Would using ActionListener in a program be considered an example of the observer pattern?

    I think you should make sure that the object which uses or displays the data is seperate from the object which contains it.
    If this is homework you may get extra marks if you display data changes in more than one way.

  • TreeView Error in MVC pattern

    <htmlb:tree id        = "ztr_dpt"
                      showTitle = "false"
                      table2 = "//MODEL/ZA_IT_TREETAB">
          </htmlb:tree>
    table2(MODEL/ZA_IT_TREETAB) structure:
    treeid   |  childid  |  text   |   statues |   click
    ztr_dpt |   001     |  aaa  |  open     |   001            
    ztr_dpt |   02       |  bbb  |  open     |   02        
    the error text:
    Type conflict in the ASSIGN statement in the program CL_HTMLB_TREE=================CP .
    why?

    the sample itab content you had shown, is it in the same fashion
    whats there in the parent field?
    it should be some thing like below
    Treeid     parent id  child id     
    S       |         |C1       |          |          |
    S       |SA       |C2       |          |          |
    S       |SAB      |C4       |          |          |
    S       |SA       |D5       |          |          |
    S       |SAC      |E        |          |
    Regards
    Raja

  • Why servlet is use a contoller in mvc pattern

    hi
    in j2ee technology we have use servlet as a controller. if i have use jsp as a controller what happen

    Nothing stops you from using a Jsp as a controller. However, using jsp as a controller is a bad idea, 'cause jsp s are suited for presentation ie for your views. Use jsps only for displaying data

  • Update methode in model-view-controller-pattern doesn't work!

    I'm writing a program in Java which contains several classes. It must be possible to produce an array random which contains Human-objects and the Humans all have a date. In the program it must be possible to set the length of the array (the number of humans to be produced) and the age of the humans. In Dutch you can see this where is written: Aantal mensen (amount of humans) and 'Maximum leeftijd' (Maximum age). Here you can find an image of the graphical user interface: http://1.bp.blogspot.com/_-b63cYMGvdM/SUb2Y62xRWI/AAAAAAAAB1A/05RLjfzUMXI/s1600-h/straightselectiondemo.JPG
    The problem I get is that use the model-view-controller-pattern. So I have a model which contains several methodes and this is written in a class which inherits form Observable. One methode is observed and this method is called 'produceerRandomArray()' (This means: produce random array). This method contains the following code:
    public void produceerMensArray() throws NegativeValueException{
         this.modelmens = Mens.getRandomMensen(this.getAantalMensen(), this.getOuderdom());
    for (int i = 0; i < this.modelmens.length; i++) {
              System.out.println(this.modelmens.toString());
    this.setChanged();
    this.notifyObservers();
    Notice the methods setChanged() and notifyObservers. In the MVC-patterns, these methods are used because they keep an eye on what's happening in this class. If this method is called, the Observers will notice it.
    So I have a button with the text 'Genereer' as you can see on the image. If you click on the button it should generate at random an array. I wrote a controller with the following code:
    package kristofvanhooymissen.sorteren;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    /**Klasse GenereerListener.
    * @author Kristof Van Hooymissen
    public class GenereerController implements ActionListener {
         protected StraightSelectionModel model;
         /**Constructor.
         *@param model Een instantie van het model wordt aan de constructor meegegeven.
         public GenereerController(StraightSelectionModel model) {
              this.model = model;
         /**Methode uit de interface ActionListener.
         * Bevat code om de toepassing te sluiten.
         public void actionPerformed(ActionEvent arg0) {
         this.model=new StraightSelectionModel();
         try{
         this.model.produceerMensArray();
         } catch (NegativeValueException e){
              System.out.println("U gaf een negatieve waarde in!");
         this.model.setAantalMensen((Integer)NumberSpinnerPanel.mensen.getValue());
         this.model.setOuderdom((Integer)NumberSpinnerPanel.leeftijd.getValue());
    StraighSelectionModel is of course my model class. Nevermind the methods setAantalMensen and setOuderdom. They are used to set the length of the array of human-objects and their age.
    Okay. If I click the button my observers will notice it because of the setChanged and notifyObservers-methods. An update-methode in a class which implements Observer.
    This method contains the follow code:
    public void update(Observable arg0,Object arg1){
              System.out.println("Update-methode");
              Mens[] temp=this.model.getMensArray();
              for (int i = 0; i < temp.length; i++) {
                   OnbehandeldeLijst.setTextArea(temp[i].toString()+"\n");
    This method should get the method out of the model-class, because the produceerRandomArray()-methode which has been called by clicking on the button will save the produce array in the model-class. The method getMensArray will put it back here in the object named temp which is an array of Mens-objects (Human-objects). Then aftwards the array should be put in the textarea of the unsorted list as you could see left on the screen on the image.
    Notice that in the beginning of this method there is a System.out.println-command to print to the screen as a test that the update-method has been called.
    The problem is that this update method won't work. My Observable class should notice that something happened with the setChanged() and notifyObservers()-methods, and after this the update class in the classes which implement Observer should me executed. But nothing happenens. My controllers works, the method in the model (produceerRandomArray() -- produce random array) has been executed, but my update-method won't work.
    Does anyone has an explanation for this? I have to get this done for my exam an the 5th of january, so everything that could help me would be nice.
    Thanks a lot,
    Kristo

    This was driving me nuts, I put in a larger SSD today going from a 120GB to a 240GB and blew away my Windows Partition to make the process easier to expand OS X, etc.  After installing windows again the only thing in device manager that wouldn't load was the Bluetooh USB Host Controller.  Tried every package in Bootcamp for version 4.0.4033 and 5.0.5033 and no luck.
    Finally came across this site:
    http://ron.dotsch.org/2011/11/how-to-get-bluetooth-to-work-in-parallels-windows- 7-64-bit-and-os-x-10-7-lion/
    1) Basically Right click the Device in Device manager, Go to Properties, Select Details tab, Choose Hardware ids from Property Drop down.   Copy the shortest Value, his was USB\VID_05AC&PID_8218 
    2) Find your bootcamp drivers and under bootcamp/drivers/apple/x64 copy AppleBluetoothInstaller64 to a folder on your desktop and unzip it.  I use winrar to Extract to the same folder.
    3) Find the files that got extracted/unzipped and open the file with notepad called AppleBT64.inf
    4) Look for the following lines:
    ; for Windows 7 only
    [Apple.NTamd64.6.1]
    ; No action
    ; OS will load in-box driver.
    Get rid of the last two lines the following:
    ; No action
    ; OS will load in-box driver.
    And add this line, paste your numbers in you got earlier for USB\VID_05ac&PID_8218:
    Apple Built-in Bluetooth=AppleBt, USB\VID_05ac&PID_8218
    So in the end it should look like the following:
    ; for Windows 7 only
    [Apple.NTamd64.6.1]
    Apple Built-in Bluetooth=AppleBt, USB\VID_05ac&PID_8218
    5) Save the changes
    6) Select Update the driver for the Bluetooth device in device manager and point it to the folder with the extracted/unzipped files and it should install the Bluetooth drivers then.
    Updated:
    Just found this link as well that does the same thing:
    http://kb.parallels.com/en/113274

  • Question on Swing, MVC and Events (Best Practices)

    Hi,
    I'm making a Swing application trying to follow the MVC pattern. To that end, I have an ApplicationView class and an ApplicationController class (as well as a DataModel). Obviously, I want to have the view as loosely coupled to the controller as possible so I can swap out the GUI later on if I want to. To that end, my controller is creating an instance of this view and passing it via its constructor a sub-class of ActionListener I created. This sub-class is an inner class of the model and basically handles all the button clicks and menu selections from the view and responds accordingly. My question is, is this the best approach or can someone reccomend a better way? Thanks in advance.

    Basically I have the same question, and I have frenetically been looking for a good answer to this... I've found that a common practice is to use actionlisteners (actually, all kinds of listeners) as nested classes in the GUI-code, also use a separate actionlistener for each event, e.g. having one actionlistener to handle events fired from one specific button, another actionlistener for another button etc.
    But this inevitally means that you get the GUI-code (more or less) interwoven with the source-code of your application. The positive effects of this is of course easy access to variables and graphical components in the rest of the code. But the downside is a potentially hard code to read and debug, also you make it difficult to separate the GUI-code from the source-code, if you for instance wanted to use the same GUI in another application.
    Take a look at the following code example (ListDemo.java) that uses several nested listener classes:
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html
    to download the app:
    http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/ListDemo.java
    Well this isn't perhaps much of an answer, it may however shed some light on matter.
    I would very much like to elaborate on this subject, so if anyone knows or has any practical examples of how to best use listeners and Swing-applications please feel free to reply this message or e-mail me personally at [email protected]
    All contributions are truly welcommed!
    Thanks
    /Mikael

  • AStar Search Logic (Bug)

    I have been working on a simple implementation of the A* Search Algorithm. I thought it was working, but apparently I didn't test it enough with different terrain movement costs (grass is easier to pass through than mountains, etc.). And now I'm wondering if my logic is even correct:
    loop through each waypoint:
        do until next waypoint is found:
            do for each adjacent node:
                if checked node is on the closed list:
                    if checked node is not on the open list:
                        make the checked node's parent = the current node
                        put the checked node on the open list
                        checked node g cost = parent node g cost + 1 (straight) or sqrt of 2 (diagonal)
                    if checked node is on the open list:
                        if the checked node's g cost < the parent node's g cost:
                            --------Should I do this next line?--------
                            switch the two nodes (in terms of parent)
                            checked node g cost = parent node g cost + 1 (straight) or sqrt of 2 (diagonal)
        let h cost = distance between current node and next waypoint
        let f cost = g cost + h cost
        make the current node the node with the lowest f cost
        put it on the closed list and remove it from the openI think that just about covers it.
    I can't seem to find good documentation on A*, so I tried several similar ways (particularly regarding the parent values), but none seem to work. The full source code can be found at http://students.hightechhigh.org/~dturnbull/11thGradeDP/Programming/AStar/AStar.zip (along with the Jar itself). A screenshot of the bug and the corresponding debug log can be found at http://students.hightechhigh.org/~dturnbull/11thGradeDP/Programming/AStar/Debug/.
    (In the screenshot, the other two paths should have the same f cost as going through the middle disregarding terrain cost. Why then, would it choose to go through the high movement cost terrain?)
    Can someone please point me in the right direction?

    First I'd like to say that, considering you're an 11th grade student, you really did a nice job! Your aplication looks nice and you have even commented your code with Javadoc standards.
    But now the criticism. ; )
    You have one big problem: your AStar class. It's far too big (almost 2000 lines!) and has far too much responsibility: it's handling events, the GUI, game logic, etc. Some of the methods are over 100 lines long(!), making them very hard to follow.
    It's best to create a non-GUI application first and when your game logic is done (and works), build a GUI around it [1].
    When creating a larger application, it can be helpfull to underline all nouns and verbs in the problem description: the nouns are your classes and the verbs are the methods from those classes.
    You could end up with these five classes:
    |                                                                      |
    | + TerrainType: enum                                                  |
    |______________________________________________________________________|
    |                                                                      |
    | - cost: int                                                          |
    | - passable: boolean                                                  |
    | - label: char                                                        |
    |______________________________________________________________________|
    |                                                                      |
    | -TerrainType(cost: int, passable: boolean, label: char) << constr >> |
    | + getCost(): int                                                     |
    | + isPassable(): boolean                                              |
    | + getLabel(): char                                                   |
    | + toString(): String                                                 |
    |______________________________________________________________________|
    |                                            |
    | + Coordinate                               |
    |____________________________________________|
    |                                            |
    | x: int                                     |
    | y: int                                     |
    | Direction: enum                            |
    |____________________________________________|
    |                                            |
    | + Coordinate(x: int, y: int): << constr >> |
    | + distance(that: Coordinate): int          |
    | + equals(o: Object): boolean               |
    | + get(direction: Direction): Coordinate    |
    | + toString(): String                       |
    |____________________________________________|
    |                                                  |
    | + Tile                                           |
    |__________________________________________________|
    |                                                  |
    | - coordinate: Coordinate                         |
    | - terrainType: TerrainType                       |
    |__________________________________________________|
    |                                                  |
    | + Tile(x: int, y: int, type: char): << constr >> |
    | + equals(o: Object): boolean                     |
    | + getCoordinate(): Coordinate                    |
    | + getTerrainType(): TerrainType                  |
    | + hashCode(): int                                |
    | + toString(): String                             |
    |__________________________________________________|
    |                                       |
    | + Path                                |
    |_______________________________________|
    |                                       |
    | - tiles: List<Tile>                   |
    | - end: Coordinate                     |
    | - cost: int                           |
    | - estimate: int                       |
    |_______________________________________|
    |                                       |
    | + Path(end: Coordinate): << constr >> |
    | + Path(that: Path): << constr >>      |
    | + add(tile: Tile): void               |
    | + compareTo(that: Path): int          |
    | + contains(tile: Tile): boolean       |
    | + getLastTile(): Tile                 |
    | + reachedEndCoordinate(): boolean     |
    | + toString(): String                  |
    |_______________________________________|
    |                                                               |
    | + Grid                                                        |
    |_______________________________________________________________|
    |                                                               |
    | - grid: Tile[][]                                              |
    | - width: int                                                  |
    | - height: int                                                 |
    |_______________________________________________________________|
    |                                                               |
    | + Grid(width: int, height: int, data: String[]): << constr >> |
    | + findPath(start: Coordinate, end: Coordinate): Path          |
    | + getNeighbours(tile: Tile): List<Tile>                       |
    | + getTile(c: Coordinate): Tile                                |
    | - processData(data: String[]): void                           |
    | + toString(): String                                          |
    |_______________________________________________________________|Note that the TerrainType is an enum [2].
    I used the following data for the grid:// 'b'=brick, 'X'=building, 'm'=mud, '.'=dummy
    String[] data = {
        "bbbbbbbbbbbbbbbb",
        "bXXXXbXXXXXXXXXb",
        "bX..XbX.......Xb",
        "bX..XbX.......Xb",
        "bX..XbX.......Xb",
        "bX..XbX.......Xb",
        "bX..XbX.......Xb",
        "bX..XbX.......Xb",
        "bX..XmX.......Xb",
        "bX..XmX.......Xb",
        "bX..XbX.......Xb",
        "bX..XbX.......Xb",
        "bX..XbX.......Xb",
        "bX..XbX.......Xb",
        "bXXXXbXXXXXXXXXb",
        "bbbbbbbbbbbbbbbb"
    }And the algorithm in the Grid class for finding a 'cheapest' path between two points (the A* algorithm) could be written as:public Path findPath(Coordinate start, Coordinate end) {
      Queue<Path> allPaths = new PriorityQueue<Path>();
      Set<Tile> visited = new HashSet<Tile>();
      Path firstPath = new Path(end);
      firstPath.add(getTile(start));
      allPaths.offer(firstPath);
      visited.add(getTile(start));
      while(!allPaths.isEmpty()) {
        Path cheapestPath = allPaths.poll();
        Tile lastTile = cheapestPath.getLastTile();
        List<Tile> neighbours = getNeighbours(lastTile);
        for(Tile tile : neighbours) {
          if(visited.add(tile)) {
            Path copy = new Path(cheapestPath);
            copy.add(tile);
            allPaths.add(copy);
            if(copy.reachedEndCoordinate()) return copy;
      return null;
    }Due to the fact that all paths are stored in a PriorityQueue, I always get the cheapest path. Of course the Path class needs to implement the Comparable interface in order to let the PriorityQueue order the paths correctly [3].
    So, I'm sorry I cannot help you with the bug in your code, but perhaps this is of help to you.
    Good luck.
    [1] Google for "MVC pattern".
    [2] If you're new to enum's, read this tutorial: http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
    [3] This tutorial explain how to do that: http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html

Maybe you are looking for

  • How export report into excel sheet automatically using SSRS 2010?

    Hi, I have created many reports using SQL Server Data Tool 2010 and at my work, we are using active batch to ran reports every month. Now question is, my boss want me to set up reports such a way that when active batch is ran, reports should be expor

  • Subscription administration for all admin-users possible?

    Hi all, at a customer exist the following scenario: one admin user creates subscription for folders, another admin user should be able to modify this subscription (in substitute function). How can I achieve this? Thanks, Andre

  • LUKS on RAID 5

    Hey guys. I'm trying to encrypt a 2TB RAID 5. I run the command: cryptsetup -c aes-xts-plain -y -s 512 luksFormat /dev/md0 After I've entered and confirmed my password, it seems to go for a few moments, and then the whole computer locks up. It cannot

  • Please help on Web Services

    Guys, I am very new in Web Service and VB.Net I downloaded sample source of VB.NET and downloaded WSDL of Service Request. What should I do with WSDL? where should this file located? In VB.NET sample source,I put server = secure.crmondemand.com also

  • Transparent Conky??

    Hello all, I have been using Arch for quite a while now and any problem I have had has been solved by reading this forum or the wiki. Well, I can't find a solution to this problem. I am running KDE with Beryl and Nvidia drivers (from pacman) and Conk