⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 discountcalculatorview.java

📁 Mandarax是一个规则引擎的纯Java实现。它支持多类型的事实和基于反映的规则
💻 JAVA
字号:
/*
 * Copyright (C) 1999-2004 <A href="http://www-ist.massey.ac.nz/JBDietrich" target="_top">Jens Dietrich</a>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package org.mandarax.examples.crm.ui;


import java.awt.*;
import java.awt.event.*;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.*;
import org.apache.log4j.BasicConfigurator;
import org.mandarax.util.ProofAnalyzer;
import org.mandarax.examples.crm.DiscountCalculator;
import org.mandarax.examples.crm.KBLoader;
import org.mandarax.examples.crm.domainmodel.*;
import org.mandarax.kernel.*;

/**
 * A swing based interface for the discount calculator.
 * The interface is actually a panel (in order to use it in an applet),
 * but the main method will open it wrapped in a frame.
 * @see org.mandarax.examples.crm.DiscountCalculator
 * @author <A href="http://www-ist.massey.ac.nz/JBDietrich" target="_top">Jens Dietrich</A>
 * @version 3.4 <7 March 05>
 * @since 1.2
 */
public class DiscountCalculatorView extends JPanel {

    // table model for customer details
	class CustomerDetailsTableModel extends javax.swing.table.AbstractTableModel {		
	    // Constructor.
	    CustomerDetailsTableModel() {
	        super ();
	    }	
	    // Get the row count.
	    public int getRowCount() {
	        return Customer.ALL.length;
	    }	
	    // Get the column count.
	    public int getColumnCount() {
	        return 5;
	    }	
	    // Get the value at the position
	    public Object getValueAt(int rowIndex, int colIndex) {
	        Customer c = Customer.ALL[rowIndex];	
	        if (colIndex == 0) return String.valueOf(c.getId());
	        else if (colIndex == 1) return c.getFirstName();
	        else if (colIndex == 2) return c.getName();
	        else if (colIndex == 3) return String.valueOf(c.getTurnover(12));
	        else if (colIndex == 4) return String.valueOf(c.getTurnover(12,KindOfPayment.COMPANY_VISA));
	        return null;
	    }	
	    // Get the column name.
	    public String getColumnName(int index) {
	        if (index == 0) return "id";
	        else if (index == 1) return "first name";
	        else if (index == 2) return "name";
	        else if (index == 3) return "turnover (last 12 month)";
	        else if (index == 4) return "turnover (last 12 month, company credit card)";
	        return "column " + index;
	    }
	}

	private JComboBox          cbxCustomers     = null;
    private JLabel             labResult        = new JLabel ("press \"calculate\"");
    private JList              listExplanation  = new JList (new DefaultListModel ());
    private JList              listKB           = new JList (new DefaultListModel ());
    private JButton            butCalculate     = new JButton ("calculate");
    private JCheckBox          checkAlias       = new JCheckBox ("use alias");
    private JTable             tabCustomerDetails = null;
    private DiscountCalculator calc             = new DiscountCalculator ();
    private Customer           selectedCustomer = null;
    private boolean            useAlias         = true;

    /**
     * Constructor.
     */
    public DiscountCalculatorView() {
        super ();
        initialize ();
    }

    /**
     * Calculate the discount for the selected customer and display it.
     */
    private void calculate() {
        calc.calculateDiscount (selectedCustomer, KBLoader.getKB ());
        displayResult ();
        butCalculate.setEnabled (false);
    }
    /**
     * Validate the KB using the JUnit runner.
     */
    private void validateKB() {
		String[] params = new String[] { KnowledgeBaseValidator.class.getName(), "-noloading" };  // this class is the test suite
		junit.swingui.TestRunner.main(params);
    }


    /**
     * Display the knowledge base.
     */
    private void displayKB() {

        // the derivation (as list, could also be displayed as tree)
        DefaultListModel listModel = (DefaultListModel) listKB.getModel ();
        listModel.removeAllElements ();
        for(Iterator iter = KBLoader.getKB ().getClauseSets ().iterator ();iter.hasNext (); ) {
        	ClauseSet nextCS = (ClauseSet)iter.next();
        	String value = nextCS.toString();
        	// try to get custom string stored as attached property
        	if (useAlias && nextCS.getProperty("alias")!=null) value = nextCS.getProperty("alias");
            listModel.addElement (value);
        }
    }

    /**
     * Display the result calculated.
     */
    private void displayResult() {

        // display the calculated discount
        labResult.setText (calc.getDiscount ().toString ());
        if(calc.getDerivation () == null) {
            return;
        }

        // the derivation (as list, could also be displayed as tree)
        DefaultListModel listModel = (DefaultListModel) listExplanation.getModel ();
        Collection usedKnowledge = ProofAnalyzer.getAppliedClauses (calc.getDerivation ());
        listModel.removeAllElements ();
        for(Iterator iter = usedKnowledge.iterator (); iter.hasNext (); ) {
        	ClauseSet nextCS = (ClauseSet)iter.next();
        	if (nextCS!=null) { 
        		String value = nextCS.toString();
        		// try to get custom string stored as attached property
        		if (useAlias && nextCS.getProperty("alias")!=null) value = nextCS.getProperty("alias");	
        		listModel.addElement (value);
        	}
        }
    }

    /**
     * Initialize the events.
     */
    private void initEvents() {
        cbxCustomers.addItemListener (new ItemListener () {
            public void itemStateChanged(ItemEvent e) {
                selectedCustomer = (Customer) e.getItem ();
                if(selectedCustomer != null) {
                    butCalculate.setEnabled (true);
                }
                reset ();
            }
        });
        butCalculate.addActionListener (new ActionListener () {
            public void actionPerformed(ActionEvent e) {
                calculate ();
            }
        });
        checkAlias.addActionListener (new ActionListener () {
            public void actionPerformed(ActionEvent e) {
                useAlias = checkAlias.isSelected ();
                displayResult ();
                displayKB ();
            }
        });
    }

    /**
     * Initialize the object.
     */
    private void initialize() {

        // the northern panel
        JPanel north       = new JPanel (new GridLayout (2, 1, 3, 3));
        JPanel inputPanel  = new JPanel (new FlowLayout (FlowLayout.CENTER));
        JPanel outputPanel = new JPanel (new FlowLayout (FlowLayout.CENTER));
        // Vector custList    = new Vector ();
        cbxCustomers = new JComboBox (Customer.ALL);
        cbxCustomers.setSelectedIndex (0);
        selectedCustomer = Customer.ALL[0];

        inputPanel.add (new JLabel ("Calculate discount for: "));
        inputPanel.add (cbxCustomers);
        inputPanel.add (butCalculate);

        JLabel labCalculated = new JLabel ("   Calculated discount: ");

        labCalculated.setFont (new Font ("dialog.bold", 1, 14));
        labCalculated.setForeground (Color.black);
        outputPanel.add (labCalculated);
        labResult.setForeground (Color.red);
        labResult.setFont (new Font ("dialog.bold", 1, 14));
        outputPanel.add (labResult);
        outputPanel.setBorder (BorderFactory.createEtchedBorder ());
        outputPanel.setBackground (Color.white);
        north.add (inputPanel);
        north.add (outputPanel);

        // the central panel
        JTabbedPane notebook         = new JTabbedPane (JTabbedPane.TOP);
        JPanel      explanationPanel = new JPanel (new BorderLayout (5, 5));

        explanationPanel.add (new JScrollPane (listExplanation),
                              BorderLayout.CENTER);
        explanationPanel.setBorder (BorderFactory.createEmptyBorder (5, 5, 5,
                5));
        notebook.add ("used rules", explanationPanel);

        JPanel tabPanel = new JPanel (new GridLayout (1, 1));

        tabCustomerDetails = new JTable(new CustomerDetailsTableModel ());

        tabCustomerDetails.sizeColumnsToFit (JTable.AUTO_RESIZE_ALL_COLUMNS);
        tabPanel.setBorder (BorderFactory.createEmptyBorder (5, 5, 5, 5));
        tabPanel.add (new JScrollPane (tabCustomerDetails));
        notebook.add ("customer details", tabPanel);
        JPanel kbPanel = new JPanel (new GridLayout (1, 1));

        kbPanel.setBorder (BorderFactory.createEmptyBorder (5, 5, 5, 5));
        kbPanel.add (new JScrollPane (listKB));
        notebook.add ("all rules", kbPanel);
        displayKB ();

        JPanel centralPanel = new JPanel (new BorderLayout (5, 5));
        centralPanel.add (
            new JLabel (
                "The calculation is based on the following rules and data:",
                JLabel.CENTER), BorderLayout.NORTH);
        centralPanel.add (notebook, BorderLayout.CENTER);

        JPanel aliasPanel = new JPanel (new FlowLayout (FlowLayout.CENTER));

        checkAlias.setSelected (useAlias);
        aliasPanel.add (checkAlias);
        centralPanel.add (aliasPanel, BorderLayout.SOUTH);

        // the main panel
        setLayout (new BorderLayout (5, 5));
        add (north, BorderLayout.NORTH);
        add (centralPanel, BorderLayout.CENTER);
        add (new JPanel (), BorderLayout.WEST);
        add (new JPanel (), BorderLayout.EAST);
        initEvents ();
    }

    /**
     * Application entry point.
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // init log4j first
        BasicConfigurator.configure ();
        
        // create UI
        JFrame wrapper = new JFrame ("Mandarax Discount Calculator");
        wrapper.getContentPane ().setLayout (new GridLayout (1, 1));

        DiscountCalculatorView view = new DiscountCalculatorView ();
        wrapper.getContentPane ().add (view);
        wrapper.setSize (700, 400);
        wrapper.setLocation (100, 100);
        wrapper.setVisible (true);
    	WindowAdapter wa = new WindowAdapter () {
    		public void windowClosing (WindowEvent e) {
    			System.exit (0);	
    		}	
    	};
    	wrapper.addWindowListener(wa);
    }

    /**
     * Reset the interface (if a new customer has been selected).
     */
    private void reset() {
        labResult.setText ("press \"calculate\"");
        listExplanation.setModel (new DefaultListModel ());
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -