mod.steps.stepmode.threads.forms.TransitionsChooser.java Source code

Java tutorial

Introduction

Here is the source code for mod.steps.stepmode.threads.forms.TransitionsChooser.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mod.steps.stepmode.threads.forms;

import mod.steps.stepmode.threads.forms.models.GeneralTableModel;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableColumnModel;
import mod.steps.stepmode.datamodels.settings.StepsOptions;
import mod.steps.stepmode.datamodels.transitions.TransitionsList;
import mod.steps.stepmode.threads.datamodels.ManualThread;
import mod.steps.stepmode.threads.forms.models.ComboRowEditor;
import mod.steps.stepmode.utils.ComponentUtils;
import org.apache.commons.lang3.StringUtils;
import pl.bsc.akrupa.components.PetriWorkspaceProperties;

/**
 * Dialog for choosing transitions in MANUAL mode.
 * 
 * @author Michal 'Wicia' Wietecha
 */
public class TransitionsChooser extends javax.swing.JFrame {

    /**
     * Creates new form TransitionsChooser
     * @param data
     * @param props
     * @param options
     */
    public TransitionsChooser(List<TransitionsList> data, PetriWorkspaceProperties props, StepsOptions options) {
        initComponents();
        initializeData(data, props, options);
        showTransitionsCombinationsTab();
    }

    public TransitionsChooser() {
        initComponents();
        initializeData();
    }

    private void initializeData(List<TransitionsList> data, PetriWorkspaceProperties props, StepsOptions options) {
        this.props = props;
        this.options = options;
        this.dataToChooseFrom = data;
        TransitionsChooser.result = null;
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    private void initializeData() {
        TransitionsChooser.result = null;
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    /**
     * For creating window.
     * 
     * @param data
     * @param props 
     * @param options 
     */
    public static void show(List<TransitionsList> data, PetriWorkspaceProperties props, StepsOptions options) {
        TransitionsChooser window = new TransitionsChooser(data, props, options);
        window.setLocationRelativeTo(null);
        window.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonAccept = new javax.swing.JButton();
        tabbledPane = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listTransitionsCombinations = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        labelInfo = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableTransitionsRepetitions = new javax.swing.JTable();
        buttonCombinations = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        areaTransitionsSet = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        buttonAccept.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        buttonAccept.setText("Accept");
        buttonAccept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAcceptActionPerformed(evt);
            }
        });

        tabbledPane.setEnabled(false);

        listTransitionsCombinations.setFont(new java.awt.Font("Courier New", 0, 14)); // NOI18N
        listTransitionsCombinations.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listTransitionsCombinationsMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(listTransitionsCombinations);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Info:");

        labelInfo.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        labelInfo.setText("Select transitions set by clicking on it and choosing Accept.");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(jPanel1Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup().addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane2)
                                .addGroup(jPanel1Layout.createSequentialGroup().addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(labelInfo).addGap(0, 78, Short.MAX_VALUE)))
                        .addContainerGap()));
        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel1).addComponent(labelInfo))
                        .addGap(18, 18, 18).addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 122,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(60, 60, 60)));

        tabbledPane.addTab("", jPanel1);

        tableTransitionsRepetitions.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
        tableTransitionsRepetitions.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][] { { null, null }, { null, null }, { null, null }, { null, null } },
                new String[] { "Title 1", "Title 2" }));
        jScrollPane1.setViewportView(tableTransitionsRepetitions);

        tabbledPane.addTab("", jScrollPane1);

        buttonCombinations.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        buttonCombinations.setText("<<< Back");
        buttonCombinations.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCombinationsActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Output transitions set",
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N

        areaTransitionsSet.setEditable(false);
        areaTransitionsSet.setColumns(20);
        areaTransitionsSet.setFont(new java.awt.Font("Courier New", 0, 14)); // NOI18N
        areaTransitionsSet.setLineWrap(true);
        areaTransitionsSet.setRows(4);
        areaTransitionsSet.setToolTipText("");
        areaTransitionsSet.setWrapStyleWord(true);
        jScrollPane3.setViewportView(areaTransitionsSet);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout
                .setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup().addGap(4, 4, 4).addComponent(jScrollPane3,
                                javax.swing.GroupLayout.PREFERRED_SIZE, 440,
                                javax.swing.GroupLayout.PREFERRED_SIZE)));
        jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup().addGap(3, 3, 3).addComponent(jScrollPane3,
                        javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(tabbledPane)
                                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(buttonAccept, javax.swing.GroupLayout.PREFERRED_SIZE, 88,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(buttonCombinations)))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                layout.createSequentialGroup().addContainerGap()
                        .addComponent(tabbledPane, javax.swing.GroupLayout.PREFERRED_SIZE, 204,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(buttonAccept, javax.swing.GroupLayout.PREFERRED_SIZE, 36,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(buttonCombinations, javax.swing.GroupLayout.PREFERRED_SIZE, 36,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonAcceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAcceptActionPerformed
        this.saveChoosenResult();
        this.dispose();
    }//GEN-LAST:event_buttonAcceptActionPerformed

    private void saveChoosenResult() {
        if (options.isSimpleStepMode()) {
            this.saveDataFromList();
            TransitionsChooser.result = this.listChoosenElement;
            ManualThread.getInstance().pauseThread(false);

        }
        if (options.isGeneralizedStepMode()) {
            this.savDataFromTable();
        }
    }

    private void savDataFromTable() {
        TransitionsList rListChoosen = new TransitionsList();
        String[] transitionsIds = getChoosenTransitionsSet();
        for (String singleId : transitionsIds) {
            rListChoosen.addToList(ComponentUtils.Transitions.findById(props, singleId));
        }
        TransitionsChooser.result = rListChoosen;
        ManualThread.getInstance().pauseThread(false);
    }

    private void saveDataFromList() {
        int selectedIndex = this.listTransitionsCombinations.getSelectedIndex();
        if (selectedIndex == -1)
            selectedIndex = 0;
        Object value = this.listModel.get(selectedIndex);
        this.listChoosenElement = TransitionsList.toTransitionsList(value, props);
    }

    private void buttonCombinationsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCombinationsActionPerformed
        showTransitionsCombinationsTab();
    }//GEN-LAST:event_buttonCombinationsActionPerformed

    private void listTransitionsCombinationsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listTransitionsCombinationsMouseClicked
        this.saveDataFromList();
        // After click show panel with transitions repetitions
        if (listChoosenElement != null && options.isGeneralizedStepMode())
            this.showTransitionsRepetitionsTab();
    }//GEN-LAST:event_listTransitionsCombinationsMouseClicked

    // -------------------------------------------------------------------------
    //    TABS MANAGEMENT
    // -------------------------------------------------------------------------

    // Only for GENERALIZED mode
    private void showTransitionsRepetitionsTab() {
        this.currentSelectedTab = SelectedTabType.REPETITIONS;
        this.initializeTable();
        this.refreshButtonsStates();
        this.tableModel.refreshLinkedComponents();
        this.tabbledPane.setSelectedIndex(currentSelectedTab.getIndex());
    }

    private void showTransitionsCombinationsTab() {
        this.currentSelectedTab = SelectedTabType.COMBINATIONS;
        this.initializeList();
        this.refreshButtonsStates();
        this.tabbledPane.setSelectedIndex(currentSelectedTab.getIndex());
    }

    private void refreshButtonsStates() {
        if (currentSelectedTab == SelectedTabType.COMBINATIONS) {
            switch (options.getType()) {
            case Simple:
                this.buttonAccept.setEnabled(true);
                this.buttonCombinations.setEnabled(false);
                break;
            case Generalized:
                this.buttonAccept.setEnabled(false);
                this.buttonCombinations.setEnabled(false);
                break;
            }
        }
        if (currentSelectedTab == SelectedTabType.REPETITIONS) {
            switch (options.getType()) {
            case Simple:
                break;
            case Generalized:
                this.buttonAccept.setEnabled(true);
                this.buttonCombinations.setEnabled(true);
                break;
            }
        }
    }

    private String[] getChoosenTransitionsSet() {
        String transitions = this.areaTransitionsSet.getText();
        if (StringUtils.isBlank(transitions)) {
            return new String[0];
        } else {
            transitions = transitions.substring(1, transitions.length() - 1);
            return transitions.split(", ");
        }
    }

    // -------------------------------------------------------------------------
    //    LIST INITIALIZATION
    // -------------------------------------------------------------------------    

    private void initializeList() {
        try {
            this.listModel = new DefaultListModel();
            for (TransitionsList list : dataToChooseFrom) {
                listModel.addElement(list.toListElement(options));
            }
            this.listTransitionsCombinations.setModel(listModel);
        } catch (Exception ex) {
        } finally {
            this.listTransitionsCombinations.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        }
    }

    // -------------------------------------------------------------------------
    //    TABLE INITIALIZATION
    // -------------------------------------------------------------------------

    private void initializeTable() {

        // Load table model
        this.tableModel = new GeneralTableModel(listChoosenElement, areaTransitionsSet);
        this.tableTransitionsRepetitions.setModel(tableModel);

        TableColumnModel tcm = this.initializeComboboxColumn();

        // Set column widths
        tcm.getColumn(0).setPreferredWidth(320);
        tcm.getColumn(1).setPreferredWidth(120);

        // Set row heighht
        tableTransitionsRepetitions.setRowHeight(20);

        tableTransitionsRepetitions.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tableTransitionsRepetitions
                .setPreferredScrollableViewportSize(tableTransitionsRepetitions.getPreferredSize());

    }

    // -------------------------------------------------------------------------
    //    COMBO-BOX INITIALIZATION
    // -------------------------------------------------------------------------    

    private TableColumnModel initializeComboboxColumn() {

        ComboRowEditor rowEditor = new ComboRowEditor(tableTransitionsRepetitions);

        int rowsCount = this.tableModel.getRowCount();
        for (int i = 0; i < rowsCount; i++) {
            String transitionId = (String) this.tableModel.getValueAt(i, 0);
            JComboBox comboBox = initializeNewComboBox(transitionId);
            rowEditor.setEditorAt(i, new DefaultCellEditor(comboBox));
        }

        tableTransitionsRepetitions.getColumn("Fire repetitions").setCellEditor(rowEditor);

        return this.tableTransitionsRepetitions.getColumnModel();
    }

    private JComboBox initializeNewComboBox(String transitionId) {
        Map<String, Integer> repetitions = listChoosenElement.getPossibleRepetitions();
        JComboBox rComboBox = new JComboBox();
        int count = repetitions.get(transitionId);
        rComboBox.setMaximumRowCount(count);
        for (int i = 1; i <= count; i++) {
            rComboBox.addItem(i + "");
        }

        return rComboBox;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea areaTransitionsSet;
    private javax.swing.JButton buttonAccept;
    private javax.swing.JButton buttonCombinations;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel labelInfo;
    private javax.swing.JList listTransitionsCombinations;
    private javax.swing.JTabbedPane tabbledPane;
    private javax.swing.JTable tableTransitionsRepetitions;
    // End of variables declaration//GEN-END:variables

    // Result variable
    private static TransitionsList result;
    private static final Object synchronizer = new Object();

    public static TransitionsList getChoosenResult(boolean deleteAfterGet) {
        synchronized (synchronizer) {
            if (result == null || result.isEmpty())
                return new TransitionsList();
            else {
                if (deleteAfterGet) {
                    TransitionsList copy = new TransitionsList(result);
                    result = null;
                    return copy;
                } else {
                    return result;
                }
            }
        }
    }

    public JTextArea getAreaTransitionsSet() {
        return this.areaTransitionsSet;
    }

    // Data variables
    private StepsOptions options;
    private PetriWorkspaceProperties props;
    private List<TransitionsList> dataToChooseFrom;

    // List variables
    private DefaultListModel listModel;
    private TransitionsList listChoosenElement;

    // Table variables
    GeneralTableModel tableModel;

    // Tabbled pane indexes
    private SelectedTabType currentSelectedTab;

    private static enum SelectedTabType {
        COMBINATIONS(0), REPETITIONS(1);

        private int index;

        private SelectedTabType(int index) {
            this.index = index;
        }

        public int getIndex() {
            return index;
        }
    };
}