Example usage for javax.swing JCheckBox addActionListener

List of usage examples for javax.swing JCheckBox addActionListener

Introduction

In this page you can find the example usage for javax.swing JCheckBox addActionListener.

Prototype

public void addActionListener(ActionListener l) 

Source Link

Document

Adds an ActionListener to the button.

Usage

From source file:com.nikonhacker.gui.EmulatorUI.java

/**
 * Create a JCheckbox corresponding to the given Output Option, reflecting its current state in prefs and changing it when modified
 * @param chip/*w  w w  . j  a  va2s  .co m*/
 * @param option one of the defined options
 * @param outputOptions the options list to initialize field from (and to which change will be written if reflectChange is true)
 * @param reflectChange if true, changing the checkbox immediately changes the option in the given outputOptions
 * @return
 */
private JCheckBox makeOutputOptionCheckBox(final int chip, final OutputOption option,
        Set<OutputOption> outputOptions, boolean reflectChange) {
    final JCheckBox checkBox = new JCheckBox(option.getKey());
    String help = (chip == Constants.CHIP_FR) ? option.getFrHelp() : option.getTxHelp();

    if (help == null)
        return null;

    checkBox.setToolTipText(help);
    checkBox.setSelected(outputOptions.contains(option));
    if (reflectChange) {
        checkBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                prefs.setOutputOption(chip, option, checkBox.isSelected());
            }
        });
    }
    return checkBox;
}

From source file:com.nikonhacker.gui.EmulatorUI.java

private void openAnalyseDialog(final int chip) {
    JTextField optionsField = new JTextField();
    JTextField destinationField = new JTextField();

    // compute and try default names for options file.
    // In order : <firmware>.dfr.txt , <firmware>.txt , dfr.txt (or the same for dtx)
    File optionsFile = new File(imageFile[chip].getParentFile(),
            FilenameUtils.getBaseName(imageFile[chip].getAbsolutePath())
                    + ((chip == Constants.CHIP_FR) ? ".dfr.txt" : ".dtx.txt"));
    if (!optionsFile.exists()) {
        optionsFile = new File(imageFile[chip].getParentFile(),
                FilenameUtils.getBaseName(imageFile[chip].getAbsolutePath()) + ".txt");
        if (!optionsFile.exists()) {
            optionsFile = new File(imageFile[chip].getParentFile(),
                    ((chip == Constants.CHIP_FR) ? "dfr.txt" : "dtx.txt"));
            if (!optionsFile.exists()) {
                optionsFile = null;// w  ww. ja  v a2s .  c  o m
            }
        }
    }
    if (optionsFile != null) {
        optionsField.setText(optionsFile.getAbsolutePath());
    }

    // compute default name for output
    File outputFile = new File(imageFile[chip].getParentFile(),
            FilenameUtils.getBaseName(imageFile[chip].getAbsolutePath()) + ".asm");
    destinationField.setText(outputFile.getAbsolutePath());

    final JCheckBox writeOutputCheckbox = new JCheckBox("Write disassembly to file");

    final FileSelectionPanel destinationFileSelectionPanel = new FileSelectionPanel("Destination file",
            destinationField, false);
    destinationFileSelectionPanel.setFileFilter(".asm", "Assembly language file (*.asm)");
    writeOutputCheckbox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            boolean writeToFile = writeOutputCheckbox.isSelected();
            destinationFileSelectionPanel.setEnabled(writeToFile);
            prefs.setWriteDisassemblyToFile(chip, writeToFile);
        }
    });

    writeOutputCheckbox.setSelected(prefs.isWriteDisassemblyToFile(chip));
    destinationFileSelectionPanel.setEnabled(prefs.isWriteDisassemblyToFile(chip));

    FileSelectionPanel fileSelectionPanel = new FileSelectionPanel(
            (chip == Constants.CHIP_FR) ? "Dfr options file" : "Dtx options file", optionsField, false);
    fileSelectionPanel.setFileFilter((chip == Constants.CHIP_FR) ? ".dfr.txt" : ".dtx.txt",
            (chip == Constants.CHIP_FR) ? "Dfr options file (*.dfr.txt)" : "Dtx options file (*.dtx.txt)");
    final JComponent[] inputs = new JComponent[] {
            //new FileSelectionPanel("Source file", sourceFile, false, dependencies),
            fileSelectionPanel, writeOutputCheckbox, destinationFileSelectionPanel,
            makeOutputOptionCheckBox(chip, OutputOption.STRUCTURE, prefs.getOutputOptions(chip), true),
            makeOutputOptionCheckBox(chip, OutputOption.ORDINAL, prefs.getOutputOptions(chip), true),
            makeOutputOptionCheckBox(chip, OutputOption.PARAMETERS, prefs.getOutputOptions(chip), true),
            makeOutputOptionCheckBox(chip, OutputOption.INT40, prefs.getOutputOptions(chip), true),
            makeOutputOptionCheckBox(chip, OutputOption.MEMORY, prefs.getOutputOptions(chip), true),
            new JLabel("(hover over the options for help. See also 'Tools/Options/Disassembler output')",
                    SwingConstants.CENTER) };

    if (JOptionPane.OK_OPTION == JOptionPane.showOptionDialog(this, inputs, "Choose analyse options",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, JOptionPane.DEFAULT_OPTION)) {
        String outputFilename = writeOutputCheckbox.isSelected() ? destinationField.getText() : null;
        boolean cancel = false;
        if (outputFilename != null) {
            if (new File(outputFilename).exists()) {
                if (JOptionPane.showConfirmDialog(this,
                        "File '" + outputFilename + "' already exists.\nDo you really want to overwrite it ?",
                        "File exists", JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION) {
                    cancel = true;
                }
            }
        }
        if (!cancel) {
            AnalyseProgressDialog analyseProgressDialog = new AnalyseProgressDialog(this,
                    framework.getPlatform(chip).getMemory());
            analyseProgressDialog.startBackgroundAnalysis(chip, optionsField.getText(), outputFilename);
            analyseProgressDialog.setVisible(true);
        }
    }
}

From source file:com.nikonhacker.gui.EmulatorUI.java

@SuppressWarnings("MagicConstant")
protected JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    JMenuItem tmpMenuItem;//from   w w w . j ava 2 s.c o m

    //Set up the file menu.
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);
    menuBar.add(fileMenu);

    //load image
    for (int chip = 0; chip < 2; chip++) {
        loadMenuItem[chip] = new JMenuItem("Load " + Constants.CHIP_LABEL[chip] + " firmware image");
        if (chip == Constants.CHIP_FR)
            loadMenuItem[chip].setMnemonic(KEY_EVENT_LOAD);
        loadMenuItem[chip].setAccelerator(KeyStroke.getKeyStroke(KEY_EVENT_LOAD, KEY_CHIP_MODIFIER[chip]));
        loadMenuItem[chip].setActionCommand(COMMAND_IMAGE_LOAD[chip]);
        loadMenuItem[chip].addActionListener(this);
        fileMenu.add(loadMenuItem[chip]);
    }

    fileMenu.add(new JSeparator());

    //decoder
    tmpMenuItem = new JMenuItem("Decode firmware");
    tmpMenuItem.setMnemonic(KeyEvent.VK_D);
    tmpMenuItem.setActionCommand(COMMAND_DECODE);
    tmpMenuItem.addActionListener(this);
    fileMenu.add(tmpMenuItem);

    //encoder
    tmpMenuItem = new JMenuItem("Encode firmware (alpha)");
    tmpMenuItem.setMnemonic(KeyEvent.VK_E);
    tmpMenuItem.setActionCommand(COMMAND_ENCODE);
    tmpMenuItem.addActionListener(this);
    //        fileMenu.add(tmpMenuItem);

    fileMenu.add(new JSeparator());

    //decoder
    tmpMenuItem = new JMenuItem("Decode lens correction data");
    //tmpMenuItem.setMnemonic(KeyEvent.VK_D);
    tmpMenuItem.setActionCommand(COMMAND_DECODE_NKLD);
    tmpMenuItem.addActionListener(this);
    fileMenu.add(tmpMenuItem);

    fileMenu.add(new JSeparator());

    //Save state
    tmpMenuItem = new JMenuItem("Save state");
    tmpMenuItem.setActionCommand(COMMAND_SAVE_STATE);
    tmpMenuItem.addActionListener(this);
    fileMenu.add(tmpMenuItem);

    //Load state
    tmpMenuItem = new JMenuItem("Load state");
    tmpMenuItem.setActionCommand(COMMAND_LOAD_STATE);
    tmpMenuItem.addActionListener(this);
    fileMenu.add(tmpMenuItem);

    fileMenu.add(new JSeparator());

    //quit
    tmpMenuItem = new JMenuItem("Quit");
    tmpMenuItem.setMnemonic(KEY_EVENT_QUIT);
    tmpMenuItem.setAccelerator(KeyStroke.getKeyStroke(KEY_EVENT_QUIT, ActionEvent.ALT_MASK));
    tmpMenuItem.setActionCommand(COMMAND_QUIT);
    tmpMenuItem.addActionListener(this);
    fileMenu.add(tmpMenuItem);

    //Set up the run menu.
    JMenu runMenu = new JMenu("Run");
    runMenu.setMnemonic(KeyEvent.VK_R);
    menuBar.add(runMenu);

    for (int chip = 0; chip < 2; chip++) {
        //emulator play
        playMenuItem[chip] = new JMenuItem("Start (or resume) " + Constants.CHIP_LABEL[chip] + " emulator");
        playMenuItem[chip].setAccelerator(KeyStroke.getKeyStroke(KEY_EVENT_RUN[chip], ActionEvent.ALT_MASK));
        playMenuItem[chip].setActionCommand(COMMAND_EMULATOR_PLAY[chip]);
        playMenuItem[chip].addActionListener(this);
        runMenu.add(playMenuItem[chip]);

        //emulator debug
        debugMenuItem[chip] = new JMenuItem("Debug " + Constants.CHIP_LABEL[chip] + " emulator");
        debugMenuItem[chip].setAccelerator(KeyStroke.getKeyStroke(KEY_EVENT_DEBUG[chip], ActionEvent.ALT_MASK));
        debugMenuItem[chip].setActionCommand(COMMAND_EMULATOR_DEBUG[chip]);
        debugMenuItem[chip].addActionListener(this);
        runMenu.add(debugMenuItem[chip]);

        //emulator pause
        pauseMenuItem[chip] = new JMenuItem("Pause " + Constants.CHIP_LABEL[chip] + " emulator");
        pauseMenuItem[chip].setAccelerator(KeyStroke.getKeyStroke(KEY_EVENT_PAUSE[chip], ActionEvent.ALT_MASK));
        pauseMenuItem[chip].setActionCommand(COMMAND_EMULATOR_PAUSE[chip]);
        pauseMenuItem[chip].addActionListener(this);
        runMenu.add(pauseMenuItem[chip]);

        //emulator step
        stepMenuItem[chip] = new JMenuItem("Step " + Constants.CHIP_LABEL[chip] + " emulator");
        stepMenuItem[chip].setAccelerator(KeyStroke.getKeyStroke(KEY_EVENT_STEP[chip], ActionEvent.ALT_MASK));
        stepMenuItem[chip].setActionCommand(COMMAND_EMULATOR_STEP[chip]);
        stepMenuItem[chip].addActionListener(this);
        runMenu.add(stepMenuItem[chip]);

        //emulator stop
        stopMenuItem[chip] = new JMenuItem("Stop and reset " + Constants.CHIP_LABEL[chip] + " emulator");
        stopMenuItem[chip].setActionCommand(COMMAND_EMULATOR_STOP[chip]);
        stopMenuItem[chip].addActionListener(this);
        runMenu.add(stopMenuItem[chip]);

        runMenu.add(new JSeparator());

        //setup breakpoints
        breakpointMenuItem[chip] = new JMenuItem("Setup " + Constants.CHIP_LABEL[chip] + " breakpoints");
        breakpointMenuItem[chip].setActionCommand(COMMAND_SETUP_BREAKPOINTS[chip]);
        breakpointMenuItem[chip].addActionListener(this);
        runMenu.add(breakpointMenuItem[chip]);

        if (chip == Constants.CHIP_FR) {
            runMenu.add(new JSeparator());
        }
    }

    //Set up the components menu.
    JMenu componentsMenu = new JMenu("Components");
    componentsMenu.setMnemonic(KeyEvent.VK_O);
    menuBar.add(componentsMenu);

    for (int chip = 0; chip < 2; chip++) {
        //CPU state
        cpuStateMenuItem[chip] = new JCheckBoxMenuItem(Constants.CHIP_LABEL[chip] + " CPU State window");
        if (chip == Constants.CHIP_FR)
            cpuStateMenuItem[chip].setMnemonic(KEY_EVENT_CPUSTATE);
        cpuStateMenuItem[chip]
                .setAccelerator(KeyStroke.getKeyStroke(KEY_EVENT_CPUSTATE, KEY_CHIP_MODIFIER[chip]));
        cpuStateMenuItem[chip].setActionCommand(COMMAND_TOGGLE_CPUSTATE_WINDOW[chip]);
        cpuStateMenuItem[chip].addActionListener(this);
        componentsMenu.add(cpuStateMenuItem[chip]);

        //memory hex editor
        memoryHexEditorMenuItem[chip] = new JCheckBoxMenuItem(
                Constants.CHIP_LABEL[chip] + " Memory hex editor");
        if (chip == Constants.CHIP_FR)
            memoryHexEditorMenuItem[chip].setMnemonic(KEY_EVENT_MEMORY);
        memoryHexEditorMenuItem[chip]
                .setAccelerator(KeyStroke.getKeyStroke(KEY_EVENT_MEMORY, KEY_CHIP_MODIFIER[chip]));
        memoryHexEditorMenuItem[chip].setActionCommand(COMMAND_TOGGLE_MEMORY_HEX_EDITOR[chip]);
        memoryHexEditorMenuItem[chip].addActionListener(this);
        componentsMenu.add(memoryHexEditorMenuItem[chip]);

        //Interrupt controller
        interruptControllerMenuItem[chip] = new JCheckBoxMenuItem(
                Constants.CHIP_LABEL[chip] + " interrupt controller");
        interruptControllerMenuItem[chip].setActionCommand(COMMAND_TOGGLE_INTERRUPT_CONTROLLER_WINDOW[chip]);
        interruptControllerMenuItem[chip].addActionListener(this);
        componentsMenu.add(interruptControllerMenuItem[chip]);

        //Programmble timers
        programmableTimersMenuItem[chip] = new JCheckBoxMenuItem(
                Constants.CHIP_LABEL[chip] + " programmable timers");
        programmableTimersMenuItem[chip].setActionCommand(COMMAND_TOGGLE_PROGRAMMABLE_TIMERS_WINDOW[chip]);
        programmableTimersMenuItem[chip].addActionListener(this);
        componentsMenu.add(programmableTimersMenuItem[chip]);

        //Serial interface
        serialInterfacesMenuItem[chip] = new JCheckBoxMenuItem(
                Constants.CHIP_LABEL[chip] + " serial interfaces");
        serialInterfacesMenuItem[chip].setActionCommand(COMMAND_TOGGLE_SERIAL_INTERFACES[chip]);
        serialInterfacesMenuItem[chip].addActionListener(this);
        componentsMenu.add(serialInterfacesMenuItem[chip]);

        // I/O
        ioPortsMenuItem[chip] = new JCheckBoxMenuItem(Constants.CHIP_LABEL[chip] + " I/O ports");
        ioPortsMenuItem[chip].setActionCommand(COMMAND_TOGGLE_IO_PORTS_WINDOW[chip]);
        ioPortsMenuItem[chip].addActionListener(this);
        componentsMenu.add(ioPortsMenuItem[chip]);

        //Serial devices
        serialDevicesMenuItem[chip] = new JCheckBoxMenuItem(Constants.CHIP_LABEL[chip] + " serial devices");
        serialDevicesMenuItem[chip].setActionCommand(COMMAND_TOGGLE_SERIAL_DEVICES[chip]);
        serialDevicesMenuItem[chip].addActionListener(this);
        componentsMenu.add(serialDevicesMenuItem[chip]);

        componentsMenu.add(new JSeparator());
    }

    //screen emulator: FR80 only
    screenEmulatorMenuItem = new JCheckBoxMenuItem("Screen emulator (FR only)");
    screenEmulatorMenuItem.setMnemonic(KEY_EVENT_SCREEN);
    screenEmulatorMenuItem.setAccelerator(KeyStroke.getKeyStroke(KEY_EVENT_SCREEN, ActionEvent.ALT_MASK));
    screenEmulatorMenuItem.setActionCommand(COMMAND_TOGGLE_SCREEN_EMULATOR);
    screenEmulatorMenuItem.addActionListener(this);
    componentsMenu.add(screenEmulatorMenuItem);

    //Component 4006: FR80 only
    component4006MenuItem = new JCheckBoxMenuItem("Component 4006 window (FR only)");
    component4006MenuItem.setMnemonic(KeyEvent.VK_4);
    component4006MenuItem.setActionCommand(COMMAND_TOGGLE_COMPONENT_4006_WINDOW);
    component4006MenuItem.addActionListener(this);
    componentsMenu.add(component4006MenuItem);

    componentsMenu.add(new JSeparator());

    //A/D converter: TX19 only for now
    adConverterMenuItem[Constants.CHIP_TX] = new JCheckBoxMenuItem(
            Constants.CHIP_LABEL[Constants.CHIP_TX] + " A/D converter (TX only)");
    adConverterMenuItem[Constants.CHIP_TX].setActionCommand(COMMAND_TOGGLE_AD_CONVERTER[Constants.CHIP_TX]);
    adConverterMenuItem[Constants.CHIP_TX].addActionListener(this);
    componentsMenu.add(adConverterMenuItem[Constants.CHIP_TX]);

    //Front panel: TX19 only
    frontPanelMenuItem = new JCheckBoxMenuItem("Front panel (TX only)");
    frontPanelMenuItem.setActionCommand(COMMAND_TOGGLE_FRONT_PANEL);
    frontPanelMenuItem.addActionListener(this);
    componentsMenu.add(frontPanelMenuItem);

    //Set up the trace menu.
    JMenu traceMenu = new JMenu("Trace");
    traceMenu.setMnemonic(KeyEvent.VK_C);
    menuBar.add(traceMenu);

    for (int chip = 0; chip < 2; chip++) {
        //memory activity viewer
        memoryActivityViewerMenuItem[chip] = new JCheckBoxMenuItem(
                Constants.CHIP_LABEL[chip] + " Memory activity viewer");
        memoryActivityViewerMenuItem[chip].setActionCommand(COMMAND_TOGGLE_MEMORY_ACTIVITY_VIEWER[chip]);
        memoryActivityViewerMenuItem[chip].addActionListener(this);
        traceMenu.add(memoryActivityViewerMenuItem[chip]);

        //disassembly
        disassemblyMenuItem[chip] = new JCheckBoxMenuItem(
                "Real-time " + Constants.CHIP_LABEL[chip] + " disassembly log");
        if (chip == Constants.CHIP_FR)
            disassemblyMenuItem[chip].setMnemonic(KEY_EVENT_REALTIME_DISASSEMBLY);
        disassemblyMenuItem[chip].setAccelerator(
                KeyStroke.getKeyStroke(KEY_EVENT_REALTIME_DISASSEMBLY, KEY_CHIP_MODIFIER[chip]));
        disassemblyMenuItem[chip].setActionCommand(COMMAND_TOGGLE_DISASSEMBLY_WINDOW[chip]);
        disassemblyMenuItem[chip].addActionListener(this);
        traceMenu.add(disassemblyMenuItem[chip]);

        //Custom logger
        customMemoryRangeLoggerMenuItem[chip] = new JCheckBoxMenuItem(
                "Custom " + Constants.CHIP_LABEL[chip] + " logger window");
        customMemoryRangeLoggerMenuItem[chip].setActionCommand(COMMAND_TOGGLE_CUSTOM_LOGGER_WINDOW[chip]);
        customMemoryRangeLoggerMenuItem[chip].addActionListener(this);
        traceMenu.add(customMemoryRangeLoggerMenuItem[chip]);

        //Call Stack logger
        callStackMenuItem[chip] = new JCheckBoxMenuItem(Constants.CHIP_LABEL[chip] + " Call stack logger");
        callStackMenuItem[chip].setActionCommand(COMMAND_TOGGLE_CALL_STACK_WINDOW[chip]);
        callStackMenuItem[chip].addActionListener(this);
        traceMenu.add(callStackMenuItem[chip]);

        //ITRON Object
        iTronObjectMenuItem[chip] = new JCheckBoxMenuItem("ITRON " + Constants.CHIP_LABEL[chip] + " Objects");
        iTronObjectMenuItem[chip].setActionCommand(COMMAND_TOGGLE_ITRON_OBJECT_WINDOW[chip]);
        iTronObjectMenuItem[chip].addActionListener(this);
        traceMenu.add(iTronObjectMenuItem[chip]);

        //ITRON Return Stack
        iTronReturnStackMenuItem[chip] = new JCheckBoxMenuItem(
                "ITRON " + Constants.CHIP_LABEL[chip] + " Return stack");
        iTronReturnStackMenuItem[chip].setActionCommand(COMMAND_TOGGLE_ITRON_RETURN_STACK_WINDOW[chip]);
        iTronReturnStackMenuItem[chip].addActionListener(this);
        traceMenu.add(iTronReturnStackMenuItem[chip]);

        traceMenu.add(new JSeparator());
    }

    //Set up the source menu.
    JMenu sourceMenu = new JMenu("Source");
    sourceMenu.setMnemonic(KEY_EVENT_SCREEN);
    menuBar.add(sourceMenu);

    // FR syscall symbols
    generateSysSymbolsMenuItem = new JMenuItem(
            "Generate " + Constants.CHIP_LABEL[Constants.CHIP_FR] + " system call symbols");
    generateSysSymbolsMenuItem.setActionCommand(COMMAND_GENERATE_SYS_SYMBOLS);
    generateSysSymbolsMenuItem.addActionListener(this);
    sourceMenu.add(generateSysSymbolsMenuItem);

    for (int chip = 0; chip < 2; chip++) {

        sourceMenu.add(new JSeparator());

        //analyse / disassemble
        analyseMenuItem[chip] = new JMenuItem("Analyse / Disassemble " + Constants.CHIP_LABEL[chip] + " code");
        analyseMenuItem[chip].setActionCommand(COMMAND_ANALYSE_DISASSEMBLE[chip]);
        analyseMenuItem[chip].addActionListener(this);
        sourceMenu.add(analyseMenuItem[chip]);

        sourceMenu.add(new JSeparator());

        //code structure
        codeStructureMenuItem[chip] = new JCheckBoxMenuItem(Constants.CHIP_LABEL[chip] + " code structure");
        codeStructureMenuItem[chip].setActionCommand(COMMAND_TOGGLE_CODE_STRUCTURE_WINDOW[chip]);
        codeStructureMenuItem[chip].addActionListener(this);
        sourceMenu.add(codeStructureMenuItem[chip]);

        //source code
        sourceCodeMenuItem[chip] = new JCheckBoxMenuItem(Constants.CHIP_LABEL[chip] + " source code");
        if (chip == Constants.CHIP_FR)
            sourceCodeMenuItem[chip].setMnemonic(KEY_EVENT_SOURCE);
        sourceCodeMenuItem[chip]
                .setAccelerator(KeyStroke.getKeyStroke(KEY_EVENT_SOURCE, KEY_CHIP_MODIFIER[chip]));
        sourceCodeMenuItem[chip].setActionCommand(COMMAND_TOGGLE_SOURCE_CODE_WINDOW[chip]);
        sourceCodeMenuItem[chip].addActionListener(this);
        sourceMenu.add(sourceCodeMenuItem[chip]);

        if (chip == Constants.CHIP_FR) {
            sourceMenu.add(new JSeparator());
        }
    }

    //Set up the tools menu.
    JMenu toolsMenu = new JMenu("Tools");
    toolsMenu.setMnemonic(KeyEvent.VK_T);
    menuBar.add(toolsMenu);

    for (int chip = 0; chip < 2; chip++) {
        // save/load memory area
        saveLoadMemoryMenuItem[chip] = new JMenuItem(
                "Save/Load " + Constants.CHIP_LABEL[chip] + " memory area");
        saveLoadMemoryMenuItem[chip].setActionCommand(COMMAND_SAVE_LOAD_MEMORY[chip]);
        saveLoadMemoryMenuItem[chip].addActionListener(this);
        toolsMenu.add(saveLoadMemoryMenuItem[chip]);

        //chip options
        chipOptionsMenuItem[chip] = new JMenuItem(Constants.CHIP_LABEL[chip] + " options");
        chipOptionsMenuItem[chip].setActionCommand(COMMAND_CHIP_OPTIONS[chip]);
        chipOptionsMenuItem[chip].addActionListener(this);
        toolsMenu.add(chipOptionsMenuItem[chip]);

        toolsMenu.add(new JSeparator());

    }

    //disassembly options
    uiOptionsMenuItem = new JMenuItem("Preferences");
    uiOptionsMenuItem.setActionCommand(COMMAND_UI_OPTIONS);
    uiOptionsMenuItem.addActionListener(this);
    toolsMenu.add(uiOptionsMenuItem);

    //Set up the help menu.
    JMenu helpMenu = new JMenu("?");
    menuBar.add(helpMenu);

    //about
    JMenuItem aboutMenuItem = new JMenuItem("About");
    aboutMenuItem.setActionCommand(COMMAND_ABOUT);
    aboutMenuItem.addActionListener(this);
    helpMenu.add(aboutMenuItem);

    //        JMenuItem testMenuItem = new JMenuItem("Test");
    //        testMenuItem.setActionCommand(COMMAND_TEST);
    //        testMenuItem.addActionListener(this);
    //        helpMenu.add(testMenuItem);

    // Global "Keep in sync" setting
    menuBar.add(Box.createHorizontalGlue());
    final JCheckBox syncEmulators = new JCheckBox("Keep emulators in sync");
    syncEmulators.setSelected(prefs.isSyncPlay());
    framework.getMasterClock().setSyncPlay(prefs.isSyncPlay());
    syncEmulators.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            prefs.setSyncPlay(syncEmulators.isSelected());
            framework.getMasterClock().setSyncPlay(syncEmulators.isSelected());
        }
    });
    menuBar.add(syncEmulators);
    return menuBar;
}

From source file:com.nikonhacker.gui.EmulatorUI.java

private void openChipOptionsDialog(final int chip) {

    // ------------------------ Disassembly options

    JPanel disassemblyOptionsPanel = new JPanel(new MigLayout("", "[left,grow][left,grow]"));

    // Prepare sample code area
    final RSyntaxTextArea listingArea = new RSyntaxTextArea(20, 90);
    SourceCodeFrame.prepareAreaFormat(chip, listingArea);

    final List<JCheckBox> outputOptionsCheckBoxes = new ArrayList<JCheckBox>();
    ActionListener areaRefresherListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Set<OutputOption> sampleOptions = EnumSet.noneOf(OutputOption.class);
                dumpOptionCheckboxes(outputOptionsCheckBoxes, sampleOptions);
                int baseAddress = framework.getPlatform(chip).getCpuState().getResetAddress();
                int lastAddress = baseAddress;
                Memory sampleMemory = new DebuggableMemory(false);
                sampleMemory.map(baseAddress, 0x100, true, true, true);
                StringWriter writer = new StringWriter();
                Disassembler disassembler;
                if (chip == Constants.CHIP_FR) {
                    sampleMemory.store16(lastAddress, 0x1781); // PUSH    RP
                    lastAddress += 2;//  w  ww .ja v a 2 s .c o  m
                    sampleMemory.store16(lastAddress, 0x8FFE); // PUSH    (FP,AC,R12,R11,R10,R9,R8)
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x83EF); // ANDCCR  #0xEF
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x9F80); // LDI:32  #0x68000000,R0
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x6800);
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x0000);
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x2031); // LD      @(FP,0x00C),R1
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0xB581); // LSL     #24,R1
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x1A40); // DMOVB   R13,@0x40
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x9310); // ORCCR   #0x10
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x8D7F); // POP     (R8,R9,R10,R11,R12,AC,FP)
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x0781); // POP    RP
                    lastAddress += 2;

                    disassembler = new Dfr();
                    disassembler.setDebugPrintWriter(new PrintWriter(new StringWriter())); // Ignore
                    disassembler.setOutputFileName(null);
                    disassembler.processOptions(new String[] { "-m", "0x" + Format.asHex(baseAddress, 8) + "-0x"
                            + Format.asHex(lastAddress, 8) + "=CODE" });
                } else {
                    sampleMemory.store32(lastAddress, 0x340B0001); // li      $t3, 0x0001
                    lastAddress += 4;
                    sampleMemory.store32(lastAddress, 0x17600006); // bnez    $k1, 0xBFC00020
                    lastAddress += 4;
                    sampleMemory.store32(lastAddress, 0x00000000); //  nop
                    lastAddress += 4;
                    sampleMemory.store32(lastAddress, 0x54400006); // bnezl   $t4, 0xBFC00028
                    lastAddress += 4;
                    sampleMemory.store32(lastAddress, 0x3C0C0000); //  ?lui   $t4, 0x0000
                    lastAddress += 4;

                    int baseAddress16 = lastAddress;
                    int lastAddress16 = baseAddress16;
                    sampleMemory.store32(lastAddress16, 0xF70064F6); // save    $ra,$s0,$s1,$s2-$s7,$fp, 0x30
                    lastAddress16 += 4;
                    sampleMemory.store16(lastAddress16, 0x6500); // nop
                    lastAddress16 += 2;
                    sampleMemory.store32(lastAddress16, 0xF7006476); // restore $ra,$s0,$s1,$s2-$s7,$fp, 0x30
                    lastAddress16 += 4;
                    sampleMemory.store16(lastAddress16, 0xE8A0); // ret
                    lastAddress16 += 2;

                    disassembler = new Dtx();
                    disassembler.setDebugPrintWriter(new PrintWriter(new StringWriter())); // Ignore
                    disassembler.setOutputFileName(null);
                    disassembler.processOptions(new String[] { "-m",
                            "0x" + Format.asHex(baseAddress, 8) + "-0x" + Format.asHex(lastAddress, 8)
                                    + "=CODE:32",
                            "-m", "0x" + Format.asHex(baseAddress16, 8) + "-0x" + Format.asHex(lastAddress16, 8)
                                    + "=CODE:16" });
                }
                disassembler.setOutputOptions(sampleOptions);
                disassembler.setMemory(sampleMemory);
                disassembler.initialize();
                disassembler.setOutWriter(writer);
                disassembler.disassembleMemRanges();
                disassembler.cleanup();
                listingArea.setText("");
                listingArea.append(writer.toString());
                listingArea.setCaretPosition(0);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };

    int i = 1;
    for (OutputOption outputOption : OutputOption.allFormatOptions) {
        JCheckBox checkBox = makeOutputOptionCheckBox(chip, outputOption, prefs.getOutputOptions(chip), false);
        if (checkBox != null) {
            outputOptionsCheckBoxes.add(checkBox);
            disassemblyOptionsPanel.add(checkBox, (i % 2 == 0) ? "wrap" : "");
            checkBox.addActionListener(areaRefresherListener);
            i++;
        }
    }
    if (i % 2 == 0) {
        disassemblyOptionsPanel.add(new JLabel(), "wrap");
    }

    // Force a refresh
    areaRefresherListener.actionPerformed(new ActionEvent(outputOptionsCheckBoxes.get(0), 0, ""));

    //        disassemblyOptionsPanel.add(new JLabel("Sample output:", SwingConstants.LEADING), "gapbottom 1, span, split 2, aligny center");
    //        disassemblyOptionsPanel.add(new JSeparator(), "span 2,wrap");
    disassemblyOptionsPanel.add(new JSeparator(), "span 2, gapleft rel, growx, wrap");
    disassemblyOptionsPanel.add(new JLabel("Sample output:"), "span 2,wrap");
    disassemblyOptionsPanel.add(new JScrollPane(listingArea), "span 2,wrap");
    disassemblyOptionsPanel.add(new JLabel("Tip: hover over the option checkboxes for help"),
            "span 2, center, wrap");

    // ------------------------ Emulation options

    JPanel emulationOptionsPanel = new JPanel(new VerticalLayout(5, VerticalLayout.LEFT));
    emulationOptionsPanel.add(new JLabel());
    JLabel warningLabel = new JLabel(
            "NOTE: these options only take effect after reloading the firmware (or performing a 'Stop and reset')");
    warningLabel.setBackground(Color.RED);
    warningLabel.setOpaque(true);
    warningLabel.setForeground(Color.WHITE);
    warningLabel.setHorizontalAlignment(SwingConstants.CENTER);
    emulationOptionsPanel.add(warningLabel);
    emulationOptionsPanel.add(new JLabel());

    final JCheckBox writeProtectFirmwareCheckBox = new JCheckBox("Write-protect firmware");
    writeProtectFirmwareCheckBox.setSelected(prefs.isFirmwareWriteProtected(chip));
    emulationOptionsPanel.add(writeProtectFirmwareCheckBox);
    emulationOptionsPanel.add(new JLabel(
            "If checked, any attempt to write to the loaded firmware area will result in an Emulator error. This can help trap spurious writes"));

    final JCheckBox dmaSynchronousCheckBox = new JCheckBox("Make DMA synchronous");
    dmaSynchronousCheckBox.setSelected(prefs.isDmaSynchronous(chip));
    emulationOptionsPanel.add(dmaSynchronousCheckBox);
    emulationOptionsPanel.add(new JLabel(
            "If checked, DMA operations will be performed immediately, pausing the CPU. Otherwise they are performed in a separate thread."));

    final JCheckBox autoEnableTimersCheckBox = new JCheckBox("Auto enable timers");
    autoEnableTimersCheckBox.setSelected(prefs.isAutoEnableTimers(chip));
    emulationOptionsPanel.add(autoEnableTimersCheckBox);
    emulationOptionsPanel
            .add(new JLabel("If checked, timers will be automatically enabled upon reset or firmware load."));

    // Log memory messages
    final JCheckBox logMemoryMessagesCheckBox = new JCheckBox("Log memory messages");
    logMemoryMessagesCheckBox.setSelected(prefs.isLogMemoryMessages(chip));
    emulationOptionsPanel.add(logMemoryMessagesCheckBox);
    emulationOptionsPanel
            .add(new JLabel("If checked, messages related to memory will be logged to the console."));

    // Log serial messages
    final JCheckBox logSerialMessagesCheckBox = new JCheckBox("Log serial messages");
    logSerialMessagesCheckBox.setSelected(prefs.isLogSerialMessages(chip));
    emulationOptionsPanel.add(logSerialMessagesCheckBox);
    emulationOptionsPanel.add(
            new JLabel("If checked, messages related to serial interfaces will be logged to the console."));

    // Log register messages
    final JCheckBox logRegisterMessagesCheckBox = new JCheckBox("Log register messages");
    logRegisterMessagesCheckBox.setSelected(prefs.isLogRegisterMessages(chip));
    emulationOptionsPanel.add(logRegisterMessagesCheckBox);
    emulationOptionsPanel.add(new JLabel(
            "If checked, warnings related to unimplemented register addresses will be logged to the console."));

    // Log pin messages
    final JCheckBox logPinMessagesCheckBox = new JCheckBox("Log pin messages");
    logPinMessagesCheckBox.setSelected(prefs.isLogPinMessages(chip));
    emulationOptionsPanel.add(logPinMessagesCheckBox);
    emulationOptionsPanel.add(new JLabel(
            "If checked, warnings related to unimplemented I/O pins will be logged to the console."));

    emulationOptionsPanel.add(new JSeparator(JSeparator.HORIZONTAL));

    // Alt mode upon Debug
    JPanel altDebugPanel = new JPanel(new FlowLayout());
    Object[] altDebugMode = EnumSet.allOf(EmulationFramework.ExecutionMode.class).toArray();
    final JComboBox altModeForDebugCombo = new JComboBox(new DefaultComboBoxModel(altDebugMode));
    for (int j = 0; j < altDebugMode.length; j++) {
        if (altDebugMode[j].equals(prefs.getAltExecutionModeForSyncedCpuUponDebug(chip))) {
            altModeForDebugCombo.setSelectedIndex(j);
        }
    }
    altDebugPanel.add(new JLabel(Constants.CHIP_LABEL[1 - chip] + " mode when " + Constants.CHIP_LABEL[chip]
            + " runs in sync Debug: "));
    altDebugPanel.add(altModeForDebugCombo);
    emulationOptionsPanel.add(altDebugPanel);
    emulationOptionsPanel
            .add(new JLabel("If 'sync mode' is selected, this is the mode the " + Constants.CHIP_LABEL[1 - chip]
                    + " chip will run in when running the " + Constants.CHIP_LABEL[chip] + " in Debug mode"));

    // Alt mode upon Step
    JPanel altStepPanel = new JPanel(new FlowLayout());
    Object[] altStepMode = EnumSet.allOf(EmulationFramework.ExecutionMode.class).toArray();
    final JComboBox altModeForStepCombo = new JComboBox(new DefaultComboBoxModel(altStepMode));
    for (int j = 0; j < altStepMode.length; j++) {
        if (altStepMode[j].equals(prefs.getAltExecutionModeForSyncedCpuUponStep(chip))) {
            altModeForStepCombo.setSelectedIndex(j);
        }
    }
    altStepPanel.add(new JLabel(Constants.CHIP_LABEL[1 - chip] + " mode when " + Constants.CHIP_LABEL[chip]
            + " runs in sync Step: "));
    altStepPanel.add(altModeForStepCombo);
    emulationOptionsPanel.add(altStepPanel);
    emulationOptionsPanel
            .add(new JLabel("If 'sync mode' is selected, this is the mode the " + Constants.CHIP_LABEL[1 - chip]
                    + " chip will run in when running the " + Constants.CHIP_LABEL[chip] + " in Step mode"));

    // ------------------------ Prepare tabbed pane

    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab(Constants.CHIP_LABEL[chip] + " Disassembly Options", null, disassemblyOptionsPanel);
    tabbedPane.addTab(Constants.CHIP_LABEL[chip] + " Emulation Options", null, emulationOptionsPanel);

    if (chip == Constants.CHIP_TX) {
        JPanel chipSpecificOptionsPanel = new JPanel(new VerticalLayout(5, VerticalLayout.LEFT));

        chipSpecificOptionsPanel.add(new JLabel("Eeprom status upon startup:"));

        ActionListener eepromInitializationRadioActionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                prefs.setEepromInitMode(Prefs.EepromInitMode.valueOf(e.getActionCommand()));
            }
        };
        JRadioButton blank = new JRadioButton("Blank");
        blank.setActionCommand(Prefs.EepromInitMode.BLANK.name());
        blank.addActionListener(eepromInitializationRadioActionListener);
        if (Prefs.EepromInitMode.BLANK.equals(prefs.getEepromInitMode()))
            blank.setSelected(true);
        JRadioButton persistent = new JRadioButton("Persistent across sessions");
        persistent.setActionCommand(Prefs.EepromInitMode.PERSISTENT.name());
        persistent.addActionListener(eepromInitializationRadioActionListener);
        if (Prefs.EepromInitMode.PERSISTENT.equals(prefs.getEepromInitMode()))
            persistent.setSelected(true);
        JRadioButton lastLoaded = new JRadioButton("Last Loaded");
        lastLoaded.setActionCommand(Prefs.EepromInitMode.LAST_LOADED.name());
        lastLoaded.addActionListener(eepromInitializationRadioActionListener);
        if (Prefs.EepromInitMode.LAST_LOADED.equals(prefs.getEepromInitMode()))
            lastLoaded.setSelected(true);

        ButtonGroup group = new ButtonGroup();
        group.add(blank);
        group.add(persistent);
        group.add(lastLoaded);

        chipSpecificOptionsPanel.add(blank);
        chipSpecificOptionsPanel.add(persistent);
        chipSpecificOptionsPanel.add(lastLoaded);

        chipSpecificOptionsPanel.add(new JLabel("Front panel type:"));
        final JComboBox frontPanelNameCombo = new JComboBox(new String[] { "D5100_small", "D5100_large" });
        if (prefs.getFrontPanelName() != null) {
            frontPanelNameCombo.setSelectedItem(prefs.getFrontPanelName());
        }
        frontPanelNameCombo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                prefs.setFrontPanelName((String) frontPanelNameCombo.getSelectedItem());
            }
        });
        chipSpecificOptionsPanel.add(frontPanelNameCombo);

        emulationOptionsPanel.add(new JSeparator(JSeparator.HORIZONTAL));

        tabbedPane.addTab(Constants.CHIP_LABEL[chip] + " specific options", null, chipSpecificOptionsPanel);
    }

    // ------------------------ Show it

    if (JOptionPane.OK_OPTION == JOptionPane.showOptionDialog(this, tabbedPane,
            Constants.CHIP_LABEL[chip] + " options", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
            null, null, JOptionPane.DEFAULT_OPTION)) {
        // save output options
        dumpOptionCheckboxes(outputOptionsCheckBoxes, prefs.getOutputOptions(chip));
        // apply
        TxCPUState.initRegisterLabels(prefs.getOutputOptions(chip));

        // save other prefs
        prefs.setFirmwareWriteProtected(chip, writeProtectFirmwareCheckBox.isSelected());
        prefs.setDmaSynchronous(chip, dmaSynchronousCheckBox.isSelected());
        prefs.setAutoEnableTimers(chip, autoEnableTimersCheckBox.isSelected());
        prefs.setLogRegisterMessages(chip, logRegisterMessagesCheckBox.isSelected());
        prefs.setLogSerialMessages(chip, logSerialMessagesCheckBox.isSelected());
        prefs.setLogPinMessages(chip, logPinMessagesCheckBox.isSelected());
        prefs.setLogMemoryMessages(chip, logMemoryMessagesCheckBox.isSelected());
        prefs.setAltExecutionModeForSyncedCpuUponDebug(chip,
                (EmulationFramework.ExecutionMode) altModeForDebugCombo.getSelectedItem());
        prefs.setAltExecutionModeForSyncedCpuUponStep(chip,
                (EmulationFramework.ExecutionMode) altModeForStepCombo.getSelectedItem());

    }
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

protected void JogMotors() {
    JDialog driver = new JDialog(mainframe, translator.get("JogMotors"), true);
    driver.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    final JButton buttonAneg = new JButton(translator.get("JogIn"));
    final JButton buttonApos = new JButton(translator.get("JogOut"));
    final JCheckBox m1i = new JCheckBox(translator.get("Invert"), machineConfiguration.m1invert);

    final JButton buttonBneg = new JButton(translator.get("JogIn"));
    final JButton buttonBpos = new JButton(translator.get("JogOut"));
    final JCheckBox m2i = new JCheckBox(translator.get("Invert"), machineConfiguration.m2invert);

    c.gridx = 0;//from   w  w w .j  av a  2  s .  co  m
    c.gridy = 0;
    driver.add(new JLabel(translator.get("Left")), c);
    c.gridx = 0;
    c.gridy = 1;
    driver.add(new JLabel(translator.get("Right")), c);

    c.gridx = 1;
    c.gridy = 0;
    driver.add(buttonAneg, c);
    c.gridx = 1;
    c.gridy = 1;
    driver.add(buttonBneg, c);

    c.gridx = 2;
    c.gridy = 0;
    driver.add(buttonApos, c);
    c.gridx = 2;
    c.gridy = 1;
    driver.add(buttonBpos, c);

    c.gridx = 3;
    c.gridy = 0;
    driver.add(m1i, c);
    c.gridx = 3;
    c.gridy = 1;
    driver.add(m2i, c);

    ActionListener driveButtons = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Object subject = e.getSource();
            if (subject == buttonApos)
                sendLineToRobot("D00 L100");
            if (subject == buttonAneg)
                sendLineToRobot("D00 L-100");
            if (subject == buttonBpos)
                sendLineToRobot("D00 R100");
            if (subject == buttonBneg)
                sendLineToRobot("D00 R-100");
            sendLineToRobot("M114");
        }
    };

    ActionListener invertButtons = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            machineConfiguration.m1invert = m1i.isSelected();
            machineConfiguration.m2invert = m2i.isSelected();
            machineConfiguration.SaveConfig();
            SendConfig();
        }
    };

    buttonApos.addActionListener(driveButtons);
    buttonAneg.addActionListener(driveButtons);

    buttonBpos.addActionListener(driveButtons);
    buttonBneg.addActionListener(driveButtons);

    m1i.addActionListener(invertButtons);
    m2i.addActionListener(invertButtons);

    sendLineToRobot("M114");
    driver.pack();
    driver.setVisible(true);
}

From source file:lu.lippmann.cdb.ext.hydviga.ui.GapFillingFrame.java

/**
 * Constructor./*from   w w  w  . j av a 2s .c  o m*/
 */
public GapFillingFrame(final AbstractTabView atv, final Instances dataSet, final Attribute attr,
        final int dateIdx, final int valuesBeforeAndAfter, final int position, final int gapsize,
        final StationsDataProvider gcp, final boolean inBatchMode) {
    super();

    setTitle("Gap filling for " + attr.name() + " ("
            + dataSet.attribute(dateIdx).formatDate(dataSet.instance(position).value(dateIdx)) + " -> "
            + dataSet.attribute(dateIdx).formatDate(dataSet.instance(position + gapsize).value(dateIdx)) + ")");
    LogoHelper.setLogo(this);

    this.atv = atv;

    this.dataSet = dataSet;
    this.attr = attr;
    this.dateIdx = dateIdx;
    this.valuesBeforeAndAfter = valuesBeforeAndAfter;
    this.position = position;
    this.gapsize = gapsize;

    this.gcp = gcp;

    final Instances testds = WekaDataProcessingUtil.buildFilteredDataSet(dataSet, 0,
            dataSet.numAttributes() - 1, Math.max(0, position - valuesBeforeAndAfter),
            Math.min(position + gapsize + valuesBeforeAndAfter, dataSet.numInstances() - 1));

    this.attrNames = WekaTimeSeriesUtil.getNamesOfAttributesWithoutGap(testds);

    this.isGapSimulated = (this.attrNames.contains(attr.name()));
    this.originaldataSet = new Instances(dataSet);
    if (this.isGapSimulated) {
        setTitle(getTitle() + " [SIMULATED GAP]");
        /*final JXLabel fictiveGapLabel=new JXLabel("                                                                        FICTIVE GAP");
        fictiveGapLabel.setForeground(Color.RED);
        fictiveGapLabel.setFont(new Font(fictiveGapLabel.getFont().getName(), Font.PLAIN,fictiveGapLabel.getFont().getSize()*2));
        final JXPanel fictiveGapPanel=new JXPanel();
        fictiveGapPanel.setLayout(new BorderLayout());
        fictiveGapPanel.add(fictiveGapLabel,BorderLayout.CENTER);
        getContentPane().add(fictiveGapPanel,BorderLayout.NORTH);*/
        this.attrNames.remove(attr.name());
        this.originalDataBeforeGapSimulation = dataSet.attributeToDoubleArray(attr.index());
        for (int i = position; i < position + gapsize; i++)
            dataSet.instance(i).setMissing(attr);
    }

    final Object[] attrNamesObj = this.attrNames.toArray();

    this.centerPanel = new JXPanel();
    this.centerPanel.setLayout(new BorderLayout());
    getContentPane().add(this.centerPanel, BorderLayout.CENTER);

    //final JXPanel algoPanel=new JXPanel();
    //getContentPane().add(algoPanel,BorderLayout.NORTH);
    final JXPanel filterPanel = new JXPanel();
    //filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.Y_AXIS));      
    filterPanel.setLayout(new GridBagLayout());
    final GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weightx = 1;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.insets = new Insets(10, 10, 10, 10);
    getContentPane().add(filterPanel, BorderLayout.WEST);

    final JXComboBox algoCombo = new JXComboBox(Algo.values());
    algoCombo.setBorder(new TitledBorder("Algorithm"));
    filterPanel.add(algoCombo, gbc);
    gbc.gridy++;

    final JXLabel infoLabel = new JXLabel("Usable = with no missing values on the period");
    //infoLabel.setBorder(new TitledBorder(""));
    filterPanel.add(infoLabel, gbc);
    gbc.gridy++;

    final JList<Object> timeSeriesList = new JList<Object>(attrNamesObj);
    timeSeriesList.setBorder(new TitledBorder("Usable time series"));
    timeSeriesList.setSelectionMode(DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    final JScrollPane jcpMap = new JScrollPane(timeSeriesList);
    jcpMap.setPreferredSize(new Dimension(225, 150));
    jcpMap.setMinimumSize(new Dimension(225, 150));
    filterPanel.add(jcpMap, gbc);
    gbc.gridy++;

    final JXPanel mapPanel = new JXPanel();
    mapPanel.setBorder(new TitledBorder(""));
    mapPanel.setLayout(new BorderLayout());
    mapPanel.add(gcp.getMapPanel(Arrays.asList(attr.name()), this.attrNames, true), BorderLayout.CENTER);
    filterPanel.add(mapPanel, gbc);
    gbc.gridy++;

    final JXLabel mssLabel = new JXLabel(
            "<html>Most similar usable serie: <i>[... computation ...]</i></html>");
    mssLabel.setBorder(new TitledBorder(""));
    filterPanel.add(mssLabel, gbc);
    gbc.gridy++;

    final JXLabel nsLabel = new JXLabel("<html>Nearest usable serie: <i>[... computation ...]</i></html>");
    nsLabel.setBorder(new TitledBorder(""));
    filterPanel.add(nsLabel, gbc);
    gbc.gridy++;

    final JXLabel ussLabel = new JXLabel("<html>Upstream serie: <i>[... computation ...]</i></html>");
    ussLabel.setBorder(new TitledBorder(""));
    filterPanel.add(ussLabel, gbc);
    gbc.gridy++;

    final JXLabel dssLabel = new JXLabel("<html>Downstream serie: <i>[... computation ...]</i></html>");
    dssLabel.setBorder(new TitledBorder(""));
    filterPanel.add(dssLabel, gbc);
    gbc.gridy++;

    final JCheckBox hideOtherSeriesCB = new JCheckBox("Hide the others series");
    hideOtherSeriesCB.setSelected(DEFAULT_HIDE_OTHER_SERIES_OPTION);
    filterPanel.add(hideOtherSeriesCB, gbc);
    gbc.gridy++;

    final JCheckBox showErrorCB = new JCheckBox("Show error on plot");
    filterPanel.add(showErrorCB, gbc);
    gbc.gridy++;

    final JCheckBox zoomCB = new JCheckBox("Auto-adjusted size");
    zoomCB.setSelected(DEFAULT_ZOOM_OPTION);
    filterPanel.add(zoomCB, gbc);
    gbc.gridy++;

    final JCheckBox multAxisCB = new JCheckBox("Multiple axis");
    filterPanel.add(multAxisCB, gbc);
    gbc.gridy++;

    final JCheckBox showEnvelopeCB = new JCheckBox("Show envelope (all algorithms, SLOW)");
    filterPanel.add(showEnvelopeCB, gbc);
    gbc.gridy++;

    final JXButton showModelButton = new JXButton("Show the model");
    filterPanel.add(showModelButton, gbc);
    gbc.gridy++;

    showModelButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            final JXFrame dialog = new JXFrame();
            dialog.setTitle("Model");
            LogoHelper.setLogo(dialog);
            dialog.getContentPane().removeAll();
            dialog.getContentPane().setLayout(new BorderLayout());
            final JTextPane modelTxtPane = new JTextPane();
            modelTxtPane.setText(gapFiller.getModel());
            modelTxtPane.setBackground(Color.WHITE);
            modelTxtPane.setEditable(false);
            final JScrollPane jsp = new JScrollPane(modelTxtPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            jsp.setSize(new Dimension(400 - 20, 400 - 20));
            dialog.getContentPane().add(jsp, BorderLayout.CENTER);
            dialog.setSize(new Dimension(400, 400));
            dialog.setLocationRelativeTo(centerPanel);
            dialog.pack();
            dialog.setVisible(true);
        }
    });

    algoCombo.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
                showModelButton.setEnabled(gapFiller.hasExplicitModel());
            } catch (final Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    timeSeriesList.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(final ListSelectionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
                mapPanel.removeAll();
                final List<String> currentlySelected = new ArrayList<String>();
                currentlySelected.add(attr.name());
                for (final Object sel : timeSeriesList.getSelectedValues())
                    currentlySelected.add(sel.toString());
                mapPanel.add(gcp.getMapPanel(currentlySelected, attrNames, true), BorderLayout.CENTER);
            } catch (final Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    hideOtherSeriesCB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
            } catch (final Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    showErrorCB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    zoomCB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    showEnvelopeCB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    multAxisCB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    this.inBatchMode = inBatchMode;

    if (!inBatchMode) {
        try {
            refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()), new int[0],
                    DEFAULT_HIDE_OTHER_SERIES_OPTION, false, DEFAULT_ZOOM_OPTION, false, false);
            showModelButton.setEnabled(gapFiller.hasExplicitModel());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    if (!inBatchMode) {
        /* automatically select computed series */
        new AbstractSimpleAsync<Void>(true) {
            @Override
            public Void execute() throws Exception {
                mostSimilar = WekaTimeSeriesSimilarityUtil.findMostSimilarTimeSerie(testds, attr, attrNames,
                        false);
                mssLabel.setText("<html>Most similar usable serie: <b>" + mostSimilar + "</b></html>");

                nearest = gcp.findNearestStation(attr.name(), attrNames);
                nsLabel.setText("<html>Nearest usable serie: <b>" + nearest + "</b></html>");

                upstream = gcp.findUpstreamStation(attr.name(), attrNames);
                if (upstream != null) {
                    ussLabel.setText("<html>Upstream usable serie: <b>" + upstream + "</b></html>");
                } else {
                    ussLabel.setText("<html>Upstream usable serie: <b>N/A</b></html>");
                }

                downstream = gcp.findDownstreamStation(attr.name(), attrNames);
                if (downstream != null) {
                    dssLabel.setText("<html>Downstream usable serie: <b>" + downstream + "</b></html>");
                } else {
                    dssLabel.setText("<html>Downstream usable serie: <b>N/A</b></html>");
                }

                timeSeriesList.setSelectedIndices(
                        new int[] { attrNames.indexOf(mostSimilar), attrNames.indexOf(nearest),
                                attrNames.indexOf(upstream), attrNames.indexOf(downstream) });

                return null;
            }

            @Override
            public void onSuccess(final Void result) {
            }

            @Override
            public void onFailure(final Throwable caught) {
                caught.printStackTrace();
            }
        }.start();
    } else {
        try {
            mostSimilar = WekaTimeSeriesSimilarityUtil.findMostSimilarTimeSerie(testds, attr, attrNames, false);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        nearest = gcp.findNearestStation(attr.name(), attrNames);
        upstream = gcp.findUpstreamStation(attr.name(), attrNames);
        downstream = gcp.findDownstreamStation(attr.name(), attrNames);
    }
}

From source file:edu.ku.brc.specify.plugins.ipadexporter.ManageDataSetsDlg.java

/**
 * //from  w w  w. ja  va 2 s . c  o m
 */
private void addUserToDS() {
    final Vector<String> wsList = new Vector<String>();
    final Vector<String> instItems = new Vector<String>();

    String addStr = getResourceString("ADD");
    instItems.add(addStr);
    wsList.add(addStr);
    for (String fullName : cloudHelper.getInstList()) {
        String[] toks = StringUtils.split(fullName, '\t');
        instItems.add(toks[0]);
        wsList.add(toks[1]);
    }

    final JTextField userNameTF = createTextField(20);
    final JTextField passwordTF = createTextField(20);
    final JLabel pwdLbl = createI18NFormLabel("Password");
    final JLabel statusLbl = createLabel("");
    final JCheckBox isNewUser = UIHelper.createCheckBox("Is New User");
    final JLabel instLbl = createI18NFormLabel("Insitution");
    final JComboBox instCmbx = UIHelper.createComboBox(instItems.toArray());

    if (instItems.size() == 2) {
        instCmbx.setSelectedIndex(1);
    }

    CellConstraints cc = new CellConstraints();
    PanelBuilder pb = new PanelBuilder(new FormLayout("p,2px,f:p:g", "p,4px,p,4px,p,4px,p,4px,p,8px,p"));

    pb.add(createI18NLabel("Add New or Existing User to DataSet"), cc.xyw(1, 1, 3));
    pb.add(createI18NFormLabel("Username"), cc.xy(1, 3));
    pb.add(userNameTF, cc.xy(3, 3));
    pb.add(pwdLbl, cc.xy(1, 5));
    pb.add(passwordTF, cc.xy(3, 5));
    pb.add(instLbl, cc.xy(1, 7));
    pb.add(instCmbx, cc.xy(3, 7));

    pb.add(isNewUser, cc.xy(3, 9));

    pb.add(statusLbl, cc.xyw(1, 11, 3));
    pb.setDefaultDialogBorder();

    pwdLbl.setVisible(false);
    passwordTF.setVisible(false);
    instLbl.setVisible(false);
    instCmbx.setVisible(false);

    final CustomDialog dlg = new CustomDialog(this, "Add User", true, OKCANCEL, pb.getPanel()) {
        @Override
        protected void okButtonPressed() {
            String usrName = userNameTF.getText();
            if (cloudHelper.isUserNameOK(usrName)) {
                String collGuid = datasetGUIDList.get(dataSetList.getSelectedIndex());
                if (cloudHelper.addUserAccessToDataSet(usrName, collGuid)) {
                    super.okButtonPressed();
                } else {
                    iPadDBExporterPlugin.setErrorMsg(statusLbl,
                            String.format("Unable to add usr: %s to the DataSet guid: %s", usrName, collGuid));
                }
            } else if (isNewUser.isSelected()) {
                String pwdStr = passwordTF.getText();
                String guid = null;
                if (instCmbx.getSelectedIndex() == 0) {
                    //                        InstDlg instDlg = new InstDlg(cloudHelper);
                    //                        if (!instDlg.isInstOK())
                    //                        {
                    //                            instDlg.createUI();
                    //                            instDlg.pack();
                    //                            centerAndShow(instDlg, 600, null);
                    //                            if (instDlg.isCancelled())
                    //                            {
                    //                                return;
                    //                            }
                    //                            //guid = instDlg.getGuid()();
                    //                        }
                } else {
                    //webSite = wsList.get(instCmbx.getSelectedIndex());

                }

                if (guid != null) {
                    String collGuid = datasetGUIDList.get(dataSetList.getSelectedIndex());
                    if (cloudHelper.addNewUser(usrName, pwdStr, guid)) {
                        if (cloudHelper.addUserAccessToDataSet(usrName, collGuid)) {
                            ManageDataSetsDlg.this.loadUsersForDataSetsIntoJList();
                            super.okButtonPressed();
                        } else {
                            iPadDBExporterPlugin.setErrorMsg(statusLbl,
                                    String.format("Unable to add%s to the DataSet %s", usrName, collGuid));
                        }
                    } else {
                        iPadDBExporterPlugin.setErrorMsg(statusLbl,
                                String.format("Unable to add%s to the DataSet %s", usrName, collGuid));
                    }
                } else {
                    // error
                }
            } else {
                iPadDBExporterPlugin.setErrorMsg(statusLbl, String.format("'%s' doesn't exist.", usrName));
            }
        }
    };

    KeyAdapter ka = new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            statusLbl.setText("");
            String usrNmStr = userNameTF.getText();
            boolean hasData = StringUtils.isNotEmpty(usrNmStr)
                    && (!isNewUser.isSelected() || StringUtils.isNotEmpty(passwordTF.getText()))
                    && UIHelper.isValidEmailAddress(usrNmStr);
            dlg.getOkBtn().setEnabled(hasData);
        }

    };
    userNameTF.addKeyListener(ka);
    passwordTF.addKeyListener(ka);

    final Color textColor = userNameTF.getForeground();

    FocusAdapter fa = new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            JTextField tf = (JTextField) e.getSource();
            if (!tf.getForeground().equals(textColor)) {
                tf.setText("");
                tf.setForeground(textColor);
            }
        }

        @Override
        public void focusLost(FocusEvent e) {
            JTextField tf = (JTextField) e.getSource();
            if (tf.getText().length() == 0) {
                tf.setText("Enter email address");
                tf.setForeground(Color.LIGHT_GRAY);
            }
        }
    };
    userNameTF.addFocusListener(fa);

    userNameTF.setText("Enter email address");
    userNameTF.setForeground(Color.LIGHT_GRAY);

    isNewUser.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean isSel = isNewUser.isSelected();
            pwdLbl.setVisible(isSel);
            passwordTF.setVisible(isSel);
            instLbl.setVisible(isSel);
            instCmbx.setVisible(isSel);

            Dimension s = dlg.getSize();
            int hgt = isNewUser.getSize().height + 4 + instCmbx.getSize().height;
            s.height += isSel ? hgt : -hgt;
            dlg.setSize(s);
        }
    });

    dlg.createUI();
    dlg.getOkBtn().setEnabled(false);

    centerAndShow(dlg);
    if (!dlg.isCancelled()) {
        loadUsersForDataSetsIntoJList();
    }
}

From source file:ffx.ui.ModelingPanel.java

private void loadCommand() {
    synchronized (this) {
        // Force Field X Command
        Element command;/*  ww w  .j  ava 2s  .co  m*/
        // Command Options
        NodeList options;
        Element option;
        // Option Values
        NodeList values;
        Element value;
        // Options may be Conditional based on previous Option values (not
        // always supplied)
        NodeList conditionalList;
        Element conditional;
        // JobPanel GUI Components that change based on command
        JPanel optionPanel;
        // Clear the previous components
        commandPanel.removeAll();
        optionsTabbedPane.removeAll();
        conditionals.clear();
        String currentCommand = (String) currentCommandBox.getSelectedItem();
        if (currentCommand == null) {
            commandPanel.validate();
            commandPanel.repaint();
            return;
        }
        command = null;
        for (int i = 0; i < commandList.getLength(); i++) {
            command = (Element) commandList.item(i);
            String name = command.getAttribute("name");
            if (name.equalsIgnoreCase(currentCommand)) {
                break;
            }
        }
        int div = splitPane.getDividerLocation();
        descriptTextArea.setText(currentCommand.toUpperCase() + ": " + command.getAttribute("description"));
        splitPane.setBottomComponent(descriptScrollPane);
        splitPane.setDividerLocation(div);
        // The "action" tells Force Field X what to do when the
        // command finishes
        commandActions = command.getAttribute("action").trim();
        // The "fileType" specifies what file types this command can execute
        // on
        String string = command.getAttribute("fileType").trim();
        String[] types = string.split(" +");
        commandFileTypes.clear();
        for (String type : types) {
            if (type.contains("XYZ")) {
                commandFileTypes.add(FileType.XYZ);
            }
            if (type.contains("INT")) {
                commandFileTypes.add(FileType.INT);
            }
            if (type.contains("ARC")) {
                commandFileTypes.add(FileType.ARC);
            }
            if (type.contains("PDB")) {
                commandFileTypes.add(FileType.PDB);
            }
            if (type.contains("ANY")) {
                commandFileTypes.add(FileType.ANY);
            }
        }
        // Determine what options are available for this command
        options = command.getElementsByTagName("Option");
        int length = options.getLength();
        for (int i = 0; i < length; i++) {
            // This Option will be enabled (isEnabled = true) unless a
            // Conditional disables it
            boolean isEnabled = true;
            option = (Element) options.item(i);
            conditionalList = option.getElementsByTagName("Conditional");
            /*
             * Currently, there can only be 0 or 1 Conditionals per Option
             * There are three types of Conditionals implemented. 1.)
             * Conditional on a previous Option, this option may be
             * available 2.) Conditional on input for this option, a
             * sub-option may be available 3.) Conditional on the presence
             * of keywords, this option may be available
             */
            if (conditionalList != null) {
                conditional = (Element) conditionalList.item(0);
            } else {
                conditional = null;
            }
            // Get the command line flag
            String flag = option.getAttribute("flag").trim();
            // Get the description
            String optionDescript = option.getAttribute("description");
            JTextArea optionTextArea = new JTextArea("  " + optionDescript.trim());
            optionTextArea.setEditable(false);
            optionTextArea.setLineWrap(true);
            optionTextArea.setWrapStyleWord(true);
            optionTextArea.setBorder(etchedBorder);
            // Get the default for this Option (if one exists)
            String defaultOption = option.getAttribute("default");
            // Option Panel
            optionPanel = new JPanel(new BorderLayout());
            optionPanel.add(optionTextArea, BorderLayout.NORTH);
            String swing = option.getAttribute("gui");
            JPanel optionValuesPanel = new JPanel(new FlowLayout());
            optionValuesPanel.setBorder(etchedBorder);
            ButtonGroup bg = null;
            if (swing.equalsIgnoreCase("CHECKBOXES")) {
                // CHECKBOXES allows selection of 1 or more values from a
                // predefined set (Analyze, for example)
                values = option.getElementsByTagName("Value");
                for (int j = 0; j < values.getLength(); j++) {
                    value = (Element) values.item(j);
                    JCheckBox jcb = new JCheckBox(value.getAttribute("name"));
                    jcb.addMouseListener(this);
                    jcb.setName(flag);
                    if (defaultOption != null && jcb.getActionCommand().equalsIgnoreCase(defaultOption)) {
                        jcb.setSelected(true);
                    }
                    optionValuesPanel.add(jcb);
                }
            } else if (swing.equalsIgnoreCase("TEXTFIELD")) {
                // TEXTFIELD takes an arbitrary String as input
                JTextField jtf = new JTextField(20);
                jtf.addMouseListener(this);
                jtf.setName(flag);
                if (defaultOption != null && defaultOption.equals("ATOMS")) {
                    FFXSystem sys = mainPanel.getHierarchy().getActive();
                    if (sys != null) {
                        jtf.setText("" + sys.getAtomList().size());
                    }
                } else if (defaultOption != null) {
                    jtf.setText(defaultOption);
                }
                optionValuesPanel.add(jtf);
            } else if (swing.equalsIgnoreCase("RADIOBUTTONS")) {
                // RADIOBUTTONS allows one choice from a set of predifined
                // values
                bg = new ButtonGroup();
                values = option.getElementsByTagName("Value");
                for (int j = 0; j < values.getLength(); j++) {
                    value = (Element) values.item(j);
                    JRadioButton jrb = new JRadioButton(value.getAttribute("name"));
                    jrb.addMouseListener(this);
                    jrb.setName(flag);
                    bg.add(jrb);
                    if (defaultOption != null && jrb.getActionCommand().equalsIgnoreCase(defaultOption)) {
                        jrb.setSelected(true);
                    }
                    optionValuesPanel.add(jrb);
                }
            } else if (swing.equalsIgnoreCase("PROTEIN")) {
                // Protein allows selection of amino acids for the protein
                // builder
                optionValuesPanel.setLayout(new BoxLayout(optionValuesPanel, BoxLayout.Y_AXIS));
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                optionValuesPanel.add(getAminoAcidPanel());
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                acidComboBox.removeAllItems();
                JButton add = new JButton("Edit");
                add.setActionCommand("PROTEIN");
                add.addActionListener(this);
                add.setAlignmentX(Button.CENTER_ALIGNMENT);
                JPanel comboPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                comboPanel.add(acidTextField);
                comboPanel.add(add);
                optionValuesPanel.add(comboPanel);
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                JButton remove = new JButton("Remove");
                add.setMinimumSize(remove.getPreferredSize());
                add.setPreferredSize(remove.getPreferredSize());
                remove.setActionCommand("PROTEIN");
                remove.addActionListener(this);
                remove.setAlignmentX(Button.CENTER_ALIGNMENT);
                comboPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                comboPanel.add(acidComboBox);
                comboPanel.add(remove);
                optionValuesPanel.add(comboPanel);
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                optionValuesPanel.add(acidScrollPane);
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                JButton reset = new JButton("Reset");
                reset.setActionCommand("PROTEIN");
                reset.addActionListener(this);
                reset.setAlignmentX(Button.CENTER_ALIGNMENT);
                optionValuesPanel.add(reset);
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                acidTextArea.setText("");
                acidTextField.setText("");
            } else if (swing.equalsIgnoreCase("NUCLEIC")) {
                // Nucleic allows selection of nucleic acids for the nucleic
                // acid builder
                optionValuesPanel.setLayout(new BoxLayout(optionValuesPanel, BoxLayout.Y_AXIS));
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                optionValuesPanel.add(getNucleicAcidPanel());
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                acidComboBox.removeAllItems();
                JButton add = new JButton("Edit");
                add.setActionCommand("NUCLEIC");
                add.addActionListener(this);
                add.setAlignmentX(Button.CENTER_ALIGNMENT);
                JPanel comboPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                comboPanel.add(acidTextField);
                comboPanel.add(add);
                optionValuesPanel.add(comboPanel);
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                JButton remove = new JButton("Remove");
                add.setMinimumSize(remove.getPreferredSize());
                add.setPreferredSize(remove.getPreferredSize());
                remove.setActionCommand("NUCLEIC");
                remove.addActionListener(this);
                remove.setAlignmentX(Button.CENTER_ALIGNMENT);
                comboPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                comboPanel.add(acidComboBox);
                comboPanel.add(remove);
                optionValuesPanel.add(comboPanel);
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                optionValuesPanel.add(acidScrollPane);
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                JButton button = new JButton("Reset");
                button.setActionCommand("NUCLEIC");
                button.addActionListener(this);
                button.setAlignmentX(Button.CENTER_ALIGNMENT);
                optionValuesPanel.add(button);
                optionValuesPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                acidTextArea.setText("");
                acidTextField.setText("");
            } else if (swing.equalsIgnoreCase("SYSTEMS")) {
                // SYSTEMS allows selection of an open system
                JComboBox<FFXSystem> jcb = new JComboBox<>(mainPanel.getHierarchy().getNonActiveSystems());
                jcb.setSize(jcb.getMaximumSize());
                jcb.addActionListener(this);
                optionValuesPanel.add(jcb);
            }
            // Set up a Conditional for this Option
            if (conditional != null) {
                isEnabled = false;
                String conditionalName = conditional.getAttribute("name");
                String conditionalValues = conditional.getAttribute("value");
                String cDescription = conditional.getAttribute("description");
                String cpostProcess = conditional.getAttribute("postProcess");
                if (conditionalName.toUpperCase().startsWith("KEYWORD")) {
                    optionPanel.setName(conditionalName);
                    String keywords[] = conditionalValues.split(" +");
                    if (activeSystem != null) {
                        Hashtable<String, Keyword> systemKeywords = activeSystem.getKeywords();
                        for (String key : keywords) {
                            if (systemKeywords.containsKey(key.toUpperCase())) {
                                isEnabled = true;
                            }
                        }
                    }
                } else if (conditionalName.toUpperCase().startsWith("VALUE")) {
                    isEnabled = true;
                    // Add listeners to the values of this option so
                    // the conditional options can be disabled/enabled.
                    for (int j = 0; j < optionValuesPanel.getComponentCount(); j++) {
                        JToggleButton jtb = (JToggleButton) optionValuesPanel.getComponent(j);
                        jtb.addActionListener(this);
                        jtb.setActionCommand("Conditional");
                    }
                    JPanel condpanel = new JPanel();
                    condpanel.setBorder(etchedBorder);
                    JLabel condlabel = new JLabel(cDescription);
                    condlabel.setEnabled(false);
                    condlabel.setName(conditionalValues);
                    JTextField condtext = new JTextField(10);
                    condlabel.setLabelFor(condtext);
                    if (cpostProcess != null) {
                        condtext.setName(cpostProcess);
                    }
                    condtext.setEnabled(false);
                    condpanel.add(condlabel);
                    condpanel.add(condtext);
                    conditionals.add(condlabel);
                    optionPanel.add(condpanel, BorderLayout.SOUTH);
                } else if (conditionalName.toUpperCase().startsWith("REFLECTION")) {
                    String[] condModifiers;
                    if (conditionalValues.equalsIgnoreCase("AltLoc")) {
                        condModifiers = activeSystem.getAltLocations();
                        if (condModifiers != null && condModifiers.length > 1) {
                            isEnabled = true;
                            bg = new ButtonGroup();
                            for (int j = 0; j < condModifiers.length; j++) {
                                JRadioButton jrbmi = new JRadioButton(condModifiers[j]);
                                jrbmi.addMouseListener(this);
                                bg.add(jrbmi);
                                optionValuesPanel.add(jrbmi);
                                if (j == 0) {
                                    jrbmi.setSelected(true);
                                }
                            }
                        }
                    } else if (conditionalValues.equalsIgnoreCase("Chains")) {
                        condModifiers = activeSystem.getChainNames();
                        if (condModifiers != null && condModifiers.length > 0) {
                            isEnabled = true;
                            for (int j = 0; j < condModifiers.length; j++) {
                                JRadioButton jrbmi = new JRadioButton(condModifiers[j]);
                                jrbmi.addMouseListener(this);
                                bg.add(jrbmi);
                                optionValuesPanel.add(jrbmi, j);
                            }
                        }
                    }
                }
            }
            optionPanel.add(optionValuesPanel, BorderLayout.CENTER);
            optionPanel.setPreferredSize(optionPanel.getPreferredSize());
            optionsTabbedPane.addTab(option.getAttribute("name"), optionPanel);
            optionsTabbedPane.setEnabledAt(optionsTabbedPane.getTabCount() - 1, isEnabled);
        }
    }
    optionsTabbedPane.setPreferredSize(optionsTabbedPane.getPreferredSize());
    commandPanel.setLayout(borderLayout);
    commandPanel.add(optionsTabbedPane, BorderLayout.CENTER);
    commandPanel.validate();
    commandPanel.repaint();
    loadLogSettings();
    statusLabel.setText("  " + createCommandInput());
}

From source file:nz.govt.natlib.ndha.manualdeposit.StructMapFileDescMgmtPresenter.java

private void addEventHandlers() {

    ActionListener actionDataChangedListener = new ActionListener() {
        public void actionPerformed(final ActionEvent evt) {
            dataChanged();// ww  w. ja va  2s.  c  o m
        }
    };

    CaretListener caretDataChangedListener = new CaretListener() {
        public void caretUpdate(final CaretEvent evt) {
            dataChanged();
        }
    };

    ItemListener itemDataChangedListener = new ItemListener() {
        public void itemStateChanged(final ItemEvent evt) {
            dataChanged();
        }
    };

    jlstDescription.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent evt) {
            descriptionListValueChanged(evt);
        }
    });
    bttnMoveUp.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent evt) {
            moveItem(true);
        }
    });
    bttnMoveDown.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent evt) {
            moveItem(false);
        }
    });
    bttnAddNew.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent evt) {
            addItem();
        }
    });
    bttnDelete.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent evt) {
            deleteItem();
        }
    });
    bttnSave.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent evt) {
            saveFileTypes();
        }
    });
    bttnCancel.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent evt) {
            final int index = jlstDescription.getSelectedIndex();
            loadData(index);
        }
    });
    bttnClose.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent evt) {
            saveIfRequired();
            theStructForm.closeForm();
        }
    });
    bttnGenMainDesc.addActionListener(new ActionListener() {
        public void actionPerformed(final ActionEvent evt) {
            generateMainDescription();
        }
    });

    textfldDescription.addCaretListener(caretDataChangedListener);
    textfldDescriptionMain.addCaretListener(caretDataChangedListener);
    textfldFilePrefix.addCaretListener(caretDataChangedListener);
    checkAllowMultiples.addActionListener(actionDataChangedListener);
    checkExtraLayers.addActionListener(actionDataChangedListener);
    checkMandatory.addActionListener(actionDataChangedListener);
    cmboPosition.addItemListener(itemDataChangedListener);

    for (Entry<String, JComponent> element : extraLayers.entrySet()) {
        // If name starts with "Allow" then it is a checkbox
        if (element.getKey().startsWith("Allow")) {
            JCheckBox field = (JCheckBox) element.getValue();
            field.addActionListener(actionDataChangedListener);
        } else {
            JTextField field = (JTextField) element.getValue();
            field.addCaretListener(caretDataChangedListener);
        }
    }

}

From source file:org.graphwalker.GUI.App.java

private JCheckBox makeNavigationCheckBoxButton(String imageName, String actionCommand, String toolTipText,
        String altText) {/*from  w w  w.  j  a  v a  2s .co  m*/
    // Create and initialize the button.
    JCheckBox button = new JCheckBox();
    button.setActionCommand(actionCommand);
    button.setToolTipText(toolTipText);
    button.addActionListener(this);

    button.setText(altText);

    return button;
}