HeatMapControls(ControlBar creator) {
    super();
    parent = creator;

    setLayout(new BorderLayout());
    super.setPreferredSize(new Dimension(255, 170));

    String[] organisms = SpeciesTable.getOrganisms();
    String[] options = new String[organisms.length + 1];

    options[0] = "None";
    for (int i = 0; i < organisms.length; i++) {
      options[i + 1] = organisms[i];
    }

    species = new JComboBox(options);
    species.addActionListener(this);
    for (String str : SpeciesTable.getOrganisms()) {}

    super.add(species, BorderLayout.SOUTH);
    super.add(new Gradient(), BorderLayout.CENTER);
    super.add(new JLabel("Least"), BorderLayout.WEST);
    super.add(new JLabel("Most"), BorderLayout.EAST);
    super.add(new JLabel("Heat Map Controls"), BorderLayout.NORTH);
    super.setVisible(true);
  }
Example #2
0
 public HeaderPanel(String heading) {
   super();
   this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
   this.setBackground(background);
   JLabel panelLabel = new JLabel(" " + heading, SwingConstants.LEFT);
   Font labelFont = new Font("Dialog", Font.BOLD, 18);
   panelLabel.setFont(labelFont);
   this.add(panelLabel);
   this.add(Box.createHorizontalGlue());
   refresh = new JButton("Refresh");
   refresh.addActionListener(this);
   this.add(refresh);
   this.add(Box.createHorizontalStrut(5));
   root = new JComboBox();
   Dimension d = root.getPreferredSize();
   d.width = 90;
   root.setPreferredSize(d);
   root.setMaximumSize(d);
   File[] roots = directoryPane.getRoots();
   for (int i = 0; i < roots.length; i++) root.addItem(roots[i].getAbsolutePath());
   this.add(root);
   root.setSelectedIndex(directoryPane.getCurrentRootIndex());
   root.addActionListener(this);
   this.add(Box.createHorizontalStrut(17));
 }
Example #3
0
  private void setupWindowAndListeners() {
    // Initialize Objects
    title = new JLabel("Coordinated Behavior Tree", JLabel.CENTER);
    treeScroller = new JScrollPane();
    treeNodes = new Vector<PBTreeNode>();
    treeView = new JTree(treeNodes);
    stratView = new JList();
    formView = new JList();
    roleView = new JList();
    subRoleView = new JList();

    // Setup our display selection drop down list
    selectorList = new Vector<String>();
    selectorList.add(PBTREE_ID);
    selectorList.add(STRAT_ID);
    selectorList.add(FORM_ID);
    selectorList.add(ROLE_ID);
    selectorList.add(SUBROLE_ID);
    displaySelector = new JComboBox(selectorList);
    displaySelector.addActionListener(this);
    treeScroller.getViewport().setView(treeView);
    treeMode = PBTREE_ID;
    treeScroller.setFocusable(false);
    treeScroller.addMouseListener(this);
    subRoleView.addMouseListener(this);

    // Setup Layout
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    setLayout(gridbag);

    // Add Items
    c.fill = GridBagConstraints.BOTH;
    c.gridwidth = GridBagConstraints.REMAINDER;
    gridbag.setConstraints(title, c);
    c.gridheight = 2;
    add(title);

    gridbag.setConstraints(displaySelector, c);
    add(displaySelector);

    c.gridheight = GridBagConstraints.REMAINDER;
    gridbag.setConstraints(treeScroller, c);
    add(treeScroller);
  }
Example #4
0
  public Animation() {
    String[] keys = {"no Animator found"};
    if (tryDir(".")) // || tryDir("BLM305") || tryDir("CSE470"))
    keys = map.keySet().toArray(keys);
    System.out.println(map.size() + " classes loaded");
    menu = new JComboBox(keys);

    pan.setLayout(new BorderLayout(GAP, GAP - 4));
    pan.setBorder(new javax.swing.border.EmptyBorder(GAP, GAP, GAP, GAP));
    pan.setBackground(COLOR);

    last = new JPanel();
    last.setPreferredSize(DIM);
    pan.add(last, "Center");

    ref.setFont(NORM);
    ref.setEditable(false);
    ref.setColumns(35);
    ref.setDragEnabled(true);
    pan.add(ref, "North");

    pan.add(bottomPanel(), "South");

    pan.setToolTipText("A collective project for BLM320");
    menu.setToolTipText("Animator classes");
    who.setToolTipText("author()");
    ref.setToolTipText("description()");

    Closer ear = new Closer();
    menu.addActionListener(ear);
    stop.addActionListener(ear);
    frm.addWindowListener(ear);

    if (map.size() > 0) setItem(0);
    frm.setContentPane(pan);
    frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frm.setLocation(scaled(120), scaled(90));
    frm.pack(); // setSize() is called here
    frm.setVisible(true);
    start();
  }
    public ChoiceField(ChoiceOption option) {
      super(option);
      this.choices = option.getChoices().toArray(new Choice[0]);

      comboBox = new JComboBox();
      for (int i = 0; i < choices.length; i++) {
        comboBox.addItem(makeEntry(choices[i].getDisplayName()));
        if (i == 0 || choices[i].isDefault()) {
          comboBox.setSelectedIndex(i);
        }
      }
      comboBox.addActionListener(
          new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              fireChangeEvent();
            }
          });

      configureEnableToggle(
          option.isInitiallyEnabled(),
          option.getDisabledValue(),
          Arrays.asList((JComponent) comboBox));
    }
Example #6
0
  /**
   * Creates basic controls for a type (AUDIO or VIDEO).
   *
   * @param type the type.
   * @return the build Component.
   */
  public static Component createBasicControls(final int type) {
    final JComboBox deviceComboBox = new JComboBox();

    deviceComboBox.setEditable(false);
    deviceComboBox.setModel(
        new DeviceConfigurationComboBoxModel(
            deviceComboBox, mediaService.getDeviceConfiguration(), type));

    JLabel deviceLabel = new JLabel(getLabelText(type));

    deviceLabel.setDisplayedMnemonic(getDisplayedMnemonic(type));
    deviceLabel.setLabelFor(deviceComboBox);

    final Container devicePanel = new TransparentPanel(new FlowLayout(FlowLayout.CENTER));

    devicePanel.setMaximumSize(new Dimension(WIDTH, 25));
    devicePanel.add(deviceLabel);
    devicePanel.add(deviceComboBox);

    final JPanel deviceAndPreviewPanel = new TransparentPanel(new BorderLayout());
    int preferredDeviceAndPreviewPanelHeight;

    switch (type) {
      case DeviceConfigurationComboBoxModel.AUDIO:
        preferredDeviceAndPreviewPanelHeight = 225;
        break;
      case DeviceConfigurationComboBoxModel.VIDEO:
        preferredDeviceAndPreviewPanelHeight = 305;
        break;
      default:
        preferredDeviceAndPreviewPanelHeight = 0;
        break;
    }
    if (preferredDeviceAndPreviewPanelHeight > 0)
      deviceAndPreviewPanel.setPreferredSize(
          new Dimension(WIDTH, preferredDeviceAndPreviewPanelHeight));
    deviceAndPreviewPanel.add(devicePanel, BorderLayout.NORTH);

    final ActionListener deviceComboBoxActionListener =
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            boolean revalidateAndRepaint = false;

            for (int i = deviceAndPreviewPanel.getComponentCount() - 1; i >= 0; i--) {
              Component c = deviceAndPreviewPanel.getComponent(i);

              if (c != devicePanel) {
                deviceAndPreviewPanel.remove(i);
                revalidateAndRepaint = true;
              }
            }

            Component preview = null;

            if ((deviceComboBox.getSelectedItem() != null) && deviceComboBox.isShowing()) {
              preview =
                  createPreview(type, deviceComboBox, deviceAndPreviewPanel.getPreferredSize());
            }

            if (preview != null) {
              deviceAndPreviewPanel.add(preview, BorderLayout.CENTER);
              revalidateAndRepaint = true;
            }

            if (revalidateAndRepaint) {
              deviceAndPreviewPanel.revalidate();
              deviceAndPreviewPanel.repaint();
            }
          }
        };

    deviceComboBox.addActionListener(deviceComboBoxActionListener);
    /*
     * We have to initialize the controls to reflect the configuration
     * at the time of creating this instance. Additionally, because the
     * video preview will stop when it and its associated controls
     * become unnecessary, we have to restart it when the mentioned
     * controls become necessary again. We'll address the two goals
     * described by pretending there's a selection in the video combo
     * box when the combo box in question becomes displayable.
     */
    deviceComboBox.addHierarchyListener(
        new HierarchyListener() {
          public void hierarchyChanged(HierarchyEvent event) {
            if ((event.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
              SwingUtilities.invokeLater(
                  new Runnable() {
                    public void run() {
                      deviceComboBoxActionListener.actionPerformed(null);
                    }
                  });
            }
          }
        });

    return deviceAndPreviewPanel;
  }
  public Payment() {
    super("Payment Process", false, true, false, true);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    label1 = new JLabel("Paymnent Number");
    label2 = new JLabel("Passenger Number");
    label3 = new JLabel("Passenger Name");
    label6 = new JLabel("Mode of Payment");
    label4 = new JLabel("Date of Payment");
    label5 = new JLabel("Amount Paid");
    label7 = new JLabel("Received By");
    text1 = new JTextField(10);
    text5 = new JTextField(10);
    p_date = new DateButton();
    p_date.setForeground(Color.red);
    combo1 = new JComboBox();
    combo2 = new JComboBox();
    combo3 = new JComboBox();
    combo4 = new JComboBox();

    combo4.addItem("Cash");
    combo4.addItem("Bank");
    combo8 = new JComboBox();
    button1 =
        new JButton("Pay", new ImageIcon(ClassLoader.getSystemResource("Images/payments.png")));
    button2 =
        new JButton(
            "Print Receipt", new ImageIcon(ClassLoader.getSystemResource("Images/print.png")));
    button3 =
        new JButton("Cancel", new ImageIcon(ClassLoader.getSystemResource("Images/exit.png")));
    button4 =
        new JButton("Search", new ImageIcon(ClassLoader.getSystemResource("Images/search.png")));
    button5 =
        new JButton("Delete", new ImageIcon(ClassLoader.getSystemResource("Images/delete.png")));
    // combo3.addItem(new)
    panel1 = new JPanel(new GridLayout(7, 2));
    panel1.setPreferredSize(new Dimension(350, 250));
    panel1.add(label1);
    panel1.add(text1);
    panel1.add(label2);
    panel1.add(combo1);
    panel1.add(label3);
    panel1.add(combo2);
    panel1.add(label6);
    panel1.add(combo4);
    panel1.add(label4);
    panel1.add(p_date);
    panel1.add(label5);
    panel1.add(combo8);
    panel1.add(label7);
    panel1.add(combo3);
    // combo8.removeAllItems();
    pane = new JPanel();
    pane.add(button1);

    pane.add(button2);
    pane.add(button3);
    pane.add(button4);

    panel3 = new JPanel();
    panel3.add(panel1);
    panel3.add(pane);

    button2.setEnabled(false);
    add(panel3);
    setSize(500, 350);
    setCombo();
    setcbr();
    generator();
    setamount();
    setLocation((screen.width - 300) / 2, ((screen.height - 300) / 2));
    setResizable(false);
    combo1.addActionListener(
        new java.awt.event.ActionListener() {

          public void actionPerformed(java.awt.event.ActionEvent e) {
            combo2.setSelectedIndex(combo1.getSelectedIndex());
            combo8.removeItem(combo8.getSelectedItem());
            setamount();
          }
        });

    button3.addActionListener(
        new java.awt.event.ActionListener() {

          public void actionPerformed(java.awt.event.ActionEvent e) {
            setVisible(true);
            dispose();
          }
        });
    button2.addActionListener(
        new java.awt.event.ActionListener() {

          public void actionPerformed(java.awt.event.ActionEvent e) {
            Receipt frm = new Receipt();
            MDIWindow.desktop.add(frm);
            frm.setVisible(true);
            button2.setEnabled(false);
          }
        });

    button1.addActionListener(
        new java.awt.event.ActionListener() {

          public void actionPerformed(java.awt.event.ActionEvent e) {

            if (combo1.getSelectedItem() == null) {
              JOptionPane.showMessageDialog(
                  null, "All Passenger have paid", "Error", JOptionPane.DEFAULT_OPTION);
              return;
            }
            if (combo2.getSelectedItem() == null) {
              JOptionPane.showMessageDialog(
                  null, "All Passenger have paid", "Error", JOptionPane.DEFAULT_OPTION);
              return;
            }
            generator();

            if (combo8.getSelectedItem() == null) {
              JOptionPane.showMessageDialog(
                  null, "The Passenger has not been booked", "ERROR", JOptionPane.DEFAULT_OPTION);
              return;
            }
            try {
              Statement statement = DBConnection.getDBConnection().createStatement();
              {
                String temp =
                    "INSERT INTO Payment (Payment_No, Pass_No, Pass_Name, Payment_Mode, Date_Payment,Amount_Paid,Received_By) VALUES ('"
                        + text1.getText()
                        + "', '"
                        + combo1.getSelectedItem()
                        + "', '"
                        + combo2.getSelectedItem()
                        + "', '"
                        + combo4.getSelectedItem()
                        + "', '"
                        + p_date.getText()
                        + "', '"
                        + combo8.getSelectedItem()
                        + "', '"
                        + combo3.getSelectedItem()
                        + "')";
                combo1.removeItem(combo1.getSelectedItem());
                combo2.removeItem(combo2.getSelectedItem());
                int result = statement.executeUpdate(temp);
                JOptionPane.showMessageDialog(
                    null, "Passenger Account updated", "Updated", JOptionPane.DEFAULT_OPTION);
              }

            } catch (SQLException sqlex) {
              sqlex.printStackTrace();
            }
            try {
              Statement statement = DBConnection.getDBConnection().createStatement();
              {
                String temp =
                    "UPDATE Passenger SET Pay_Status='Paid'"
                        + "WHERE Pass_NO LIKE  '"
                        + combo1.getSelectedItem()
                        + "'";
                int result = statement.executeUpdate(temp);
              }

            } catch (SQLException sqlex) {
              sqlex.printStackTrace();
            }
            button1.setEnabled(false);
            button2.setEnabled(true);
          }
        });
    button4.addActionListener(
        new ActionListener() {

          public void actionPerformed(ActionEvent e) {
            try {
              if (!text1.equals("")) {

                Statement statement = DBConnection.getDBConnection().createStatement();
                String query =
                    ("SELECT * FROM Payment where Payment_No ='" + text1.getText() + "'");

                ResultSet rs = statement.executeQuery(query);
                display(rs);
                statement.close();
              }
            } catch (SQLException sqlex) {
              sqlex.printStackTrace();
            }
            setVisible(true);
          }
        });
  }
Example #8
0
    OpPanel(PreferencesExt prefs, boolean isAccess) {
      this.prefs = prefs;
      this.isAccess = isAccess;
      ta = new TextHistoryPane(true);
      infoWindow =
          new IndependentWindow("Details", BAMutil.getImage("netcdfUI"), new JScrollPane(ta));
      Rectangle bounds = (Rectangle) prefs.getBean(FRAME_SIZE, new Rectangle(200, 50, 500, 700));
      infoWindow.setBounds(bounds);

      topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));

      // which server
      serverCB = new JComboBox();
      serverCB.setModel(manage.getServersCB().getModel());
      serverCB.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              String server = (String) serverCB.getSelectedItem();
              setServer(server);
            }
          });

      // serverCB.setModel(manage.getServers().getModel());
      topPanel.add(new JLabel("server:"));
      topPanel.add(serverCB);

      // the date selectors
      startDateField = new JTextArea("                    ");
      endDateField = new JTextArea("                    ");

      topPanel.add(new JLabel("Start Date:"));
      topPanel.add(startDateField);
      topPanel.add(new JLabel("End Date:"));
      topPanel.add(endDateField);

      AbstractAction showAction =
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              showLogs();
            }
          };
      BAMutil.setActionProperties(showAction, "Import", "get logs", false, 'G', -1);
      BAMutil.addActionToContainer(topPanel, showAction);

      AbstractAction filterAction =
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              Boolean state = (Boolean) getValue(BAMutil.STATE);
              removeTestReq = state.booleanValue();
            }
          };
      BAMutil.setActionProperties(filterAction, "time", "remove test Requests", true, 'F', -1);
      BAMutil.addActionToContainer(topPanel, filterAction);

      AbstractAction filter2Action =
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              Boolean state = (Boolean) getValue(BAMutil.STATE);
              problemsOnly = state.booleanValue();
            }
          };
      BAMutil.setActionProperties(filter2Action, "time", "only show problems", true, 'F', -1);
      BAMutil.addActionToContainer(topPanel, filter2Action);

      AbstractAction infoAction =
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              Formatter f = new Formatter();
              showInfo(f);
              ta.setText(f.toString());
              infoWindow.show();
            }
          };
      BAMutil.setActionProperties(
          infoAction, "Information", "info on selected logs", false, 'I', -1);
      BAMutil.addActionToContainer(topPanel, infoAction);

      setLayout(new BorderLayout());
      add(topPanel, BorderLayout.NORTH);
    }
  public ODEWizardScalaSci() {
    editingClassName = "Lorenz";
    systemOrder = 3; // the order of ODE system

    copyTemplateButton =
        new JButton("1. Copy and Edit Template", new ImageIcon("/scalaLab.jar/yellow-ball.gif"));
    generateEditingButton = new JButton("2. Generate Java Class", new ImageIcon("./blue-ball.gif"));
    saveJavaClassButton =
        new JButton("3. Save Java Class", new ImageIcon("scalaLab.jar/red-ball.gif"));
    compileJavaClassButton =
        new JButton("4.a. Java Compile - External Compiler", new ImageIcon("blue-ball.gif"));
    compileJavaInternalCompilerButton =
        new JButton("4.b. Java Compile - Internal Compiler", new ImageIcon("blue-ball.gif"));
    generateScriptCodeButton =
        new JButton("Generate scalaSci Script", new ImageIcon("red-ball.gif"));

    ODEWizardFrame = new JFrame("ODE Wizard for scalaSci with Java implementation of. ODEs");

    editPanel = new JPanel();
    editPanel.setLayout(new GridLayout(1, 2));

    paramPanel = new JPanel(new GridLayout(1, 4));
    availODEMethods.add("ODErke");
    availODEMethods.add("ODEmultistep");
    availODEMethods.add("ODEdiffsys");
    ODEselectMethodLabel = new JLabel("ODE method: ");
    ODEselectMethodComboBox = new JComboBox(availODEMethods);
    ODEselectMethodComboBox.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            ODESolveMethod = ODEselectMethodComboBox.getSelectedIndex();
            updateTemplateText();
            templateTextArea.setText(templateText);
            currentlySelectedLabel.setText(
                "Selected Method: " + (String) availODEMethods.get(ODESolveMethod));
          }
        });

    JLabel javaFileTextLabel = new JLabel("Java File Name: ");
    javaFileTextBox = new JTextField(editingClassName);
    javaFileTextBox.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            editingClassName = javaFileTextBox.getText();
            String updatedStatusText = prepareStatusText();
            statusAreaTop.setText(updatedStatusText);
          }
        });

    JLabel systemOrderLabel = new JLabel("System order: ");
    systemOrderText = new JTextField(String.valueOf(systemOrder));
    systemOrderText.addActionListener(new editSystemOrder());
    JPanel javaFilePanel = new JPanel();
    javaFilePanel.add(javaFileTextLabel);
    javaFilePanel.add(javaFileTextBox);
    JPanel systemOrderPanel = new JPanel();
    systemOrderPanel.add(systemOrderLabel);
    systemOrderPanel.add(systemOrderText);

    paramMethodPanel = new JPanel();
    paramMethodPanel.add(ODEselectMethodLabel);
    paramMethodPanel.add(ODEselectMethodComboBox);
    paramPanel.add(paramMethodPanel);
    paramPanel.add(javaFilePanel);
    paramPanel.add(systemOrderPanel);
    currentlySelectedLabel =
        new JLabel("Selected Method: " + (String) availODEMethods.get(ODESolveMethod));
    paramPanel.add(currentlySelectedLabel);

    statusPanel = new JPanel(new GridLayout(2, 1));
    statusAreaTop = new JTextArea();
    statusAreaTop.setFont(new Font("Arial", Font.BOLD, 16));
    String statusText = prepareStatusText();

    statusAreaTop.setText(statusText);
    statusAreaBottom = new JTextArea();
    statusAreaBottom.setText(
        "Step1:  Copy and edit the template ODE  (implements the famous Lorenz chaotic system),\n"
            + "Then set the name of your Java Class (instead of \"Lorenz\"),  without the extension .java\n"
            + "Also set the proper order (i.e. number of equations and variables) of your system. ");
    statusPanel.add(statusAreaTop);
    statusPanel.add(statusAreaBottom);

    templateTextArea = new JTextArea();
    updateTemplateText();

    templateTextArea.setFont(new Font("Arial", Font.ITALIC, 12));
    templateTextArea.setText(templateText);
    templateScrollPane = new JScrollPane();
    templateViewPort = templateScrollPane.getViewport();
    templateViewPort.add(templateTextArea);

    ODEWizardTextArea = new JTextArea();
    ODEWizardText = "";
    ODEWizardTextArea.setText(ODEWizardText);
    ODEWizardTextArea.setFont(new Font("Arial", Font.BOLD, 12));

    ODEWizardScrollPane = new JScrollPane();
    wizardViewPort = ODEWizardScrollPane.getViewport();
    wizardViewPort.add(ODEWizardTextArea);

    editPanel.add(ODEWizardScrollPane);
    editPanel.add(templateScrollPane);

    // Step 1: copy template of ODE implementation from the
    // templateTextArea to ODEWizardTextArea
    copyTemplateButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            ODEWizardTextArea.setText(templateTextArea.getText());
            generateEditingButton.setEnabled(true);
            statusAreaBottom.setText(
                "Step2:  If you have implemented correctly your ODE, the wizard completes the ready to compile Java class");
          }
        });

    // Step 2: generate Java Class from template
    JPanel buttonPanel = new JPanel();
    generateEditingButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            String editingODE = ODEWizardTextArea.getText();
            String classImplementationString = // "package javaPluggins; \n"+
                "import  numal.*; \n\n"
                    + "public class "
                    + editingClassName
                    + " extends Object \n             implements "
                    + implementingInterfaces[ODESolveMethod]
                    + " \n \n "
                    + "{ \n";

            classImplementationString += (editingODE + "}\n");

            ODEWizardTextArea.setText(classImplementationString);
            saveJavaClassButton.setEnabled(true);
            statusAreaBottom.setText(
                "Step3:  The generated Java source is ready, you can check it, and then proceed to save.");
          }
        });

    // Step 3: save generated Java Class on disk
    saveJavaClassButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            String currentWorkingDirectory = Directory.Current().get().path();
            JFileChooser chooser = new JFileChooser(currentWorkingDirectory);
            chooser.setSelectedFile(new File(editingClassName + ".java"));
            int ret = chooser.showSaveDialog(ODEWizardFrame);

            if (ret != JFileChooser.APPROVE_OPTION) {
              return;
            }
            File f = chooser.getSelectedFile();
            try {
              PrintWriter out = new PrintWriter(f);
              String javaCodeText = ODEWizardTextArea.getText();
              out.write(javaCodeText);
              out.close();
              // update the notion  of the working directory
              String fullPathOfSavedFile = f.getAbsolutePath();
              GlobalValues.workingDir =
                  fullPathOfSavedFile.substring(
                      0, fullPathOfSavedFile.lastIndexOf(File.separatorChar) + 1);

              compileJavaClassButton.setEnabled(true);
              compileJavaInternalCompilerButton.setEnabled(true);
              statusAreaBottom.setText(
                  "Step4:  The Java source file was saved to disk,  \n "
                      + "you can proceed to compile and load the corresponding class file");
            } catch (java.io.FileNotFoundException enf) {
              System.out.println("File " + f.getName() + " not found");
              enf.printStackTrace();
            } catch (Exception eOther) {
              System.out.println("Exception trying to create PrintWriter");
              eOther.printStackTrace();
            }
          }
        });

    // Step 4: Compile the generated Java class
    compileJavaClassButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            String currentWorkingDirectory = GlobalValues.workingDir;
            JFileChooser chooser = new JFileChooser(currentWorkingDirectory);
            int ret = chooser.showOpenDialog(ODEWizardFrame);

            if (ret != JFileChooser.APPROVE_OPTION) {
              return;
            }
            File f = chooser.getSelectedFile();
            String javaFile = null;
            try {
              javaFile = f.getCanonicalPath();
            } catch (IOException ex) {
              System.out.println("I/O Exception in getCanonicalPath");
              ex.printStackTrace();
            }

            //   extract the path specification of the generated Java class that implements the ODE
            // solution method,
            //    in order to update the ScalaSci class path
            String SelectedFileWithPath = f.getAbsolutePath();
            String SelectedFilePathOnly =
                SelectedFileWithPath.substring(
                    0, SelectedFileWithPath.lastIndexOf(File.separatorChar));

            if (GlobalValues.ScalaSciClassPath.length() == 0) GlobalValues.ScalaSciClassPath = ".";
            if (GlobalValues.ScalaSciClassPath.indexOf(SelectedFilePathOnly) == -1) {
              GlobalValues.ScalaSciClassPathComponents.add(0, SelectedFilePathOnly);
              GlobalValues.ScalaSciClassPath =
                  GlobalValues.ScalaSciClassPath + File.pathSeparator + SelectedFilePathOnly;
            }
            // update also the ScalaSciClassPath property
            StringBuilder fileStr = new StringBuilder();
            Enumeration enumDirs = GlobalValues.ScalaSciClassPathComponents.elements();
            while (enumDirs.hasMoreElements()) {
              Object ce = enumDirs.nextElement();
              fileStr.append(File.pathSeparator + (String) ce);
            }
            GlobalValues.settings.setProperty("ScalaSciClassPath", fileStr.toString());

            ClassLoader parentClassLoader = getClass().getClassLoader();
            GlobalValues.extensionClassLoader =
                new ExtensionClassLoader(GlobalValues.ScalaSciClassPath, parentClassLoader);

            // update GUI components to account for the updated ScalaSci classpath
            scalaExec.scalaLab.scalaLab.updateTree();

            boolean compilationSucccess = true;

            String tempFileName = "";
            tempFileName =
                javaFile + ".java"; // public classes and Java files should have the same name

            String[] command = new String[6];
            command[0] = "javac";
            command[1] = "-cp";
            command[2] = GlobalValues.jarFilePath + File.pathSeparator + GlobalValues.homeDir;
            command[3] = "-d"; // where to place output class files
            command[4] = SelectedFilePathOnly; //  the path to save the compiled class files
            command[5] = javaFile; // full filename to compile

            String compileCommandString =
                command[0]
                    + "  "
                    + command[1]
                    + "  "
                    + command[2]
                    + " "
                    + command[3]
                    + " "
                    + command[4]
                    + " "
                    + command[5];

            System.out.println("compileCommand Java= " + compileCommandString);

            try {
              Runtime rt = Runtime.getRuntime();
              Process javaProcess = rt.exec(command);
              // an error message?
              StreamGobbler errorGobbler = new StreamGobbler(javaProcess.getErrorStream(), "ERROR");

              // any output?
              StreamGobbler outputGobbler =
                  new StreamGobbler(javaProcess.getInputStream(), "OUTPUT");

              // kick them off
              errorGobbler.start();
              outputGobbler.start();

              // any error???
              javaProcess.waitFor();
              int rv = javaProcess.exitValue();
              String commandString = command[0] + "  " + command[1] + "  " + command[2];
              if (rv == 0) {
                System.out.println("Process:  " + commandString + "  exited successfully ");
                generateScriptCodeButton.setEnabled(true);
                statusAreaBottom.setText(
                    "Step5:  You can proceed now to create a draft script that utilizes your Java-based  ODE integrator");
              } else
                System.out.println(
                    "Process:  " + commandString + "  exited with error, error value = " + rv);

            } catch (IOException exio) {
              System.out.println("IOException trying to executing " + command);
              exio.printStackTrace();

            } catch (InterruptedException ie) {
              System.out.println("Interrupted Exception  trying to executing " + command);
              ie.printStackTrace();
            }
          }
        });

    // Compile with the internal compiler
    compileJavaInternalCompilerButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            String currentWorkingDirectory = GlobalValues.workingDir;
            JFileChooser chooser = new JFileChooser(currentWorkingDirectory);
            int ret = chooser.showOpenDialog(ODEWizardFrame);

            if (ret != JFileChooser.APPROVE_OPTION) {
              return;
            }
            File f = chooser.getSelectedFile();
            String javaFile = null;
            try {
              javaFile = f.getCanonicalPath();
            } catch (IOException ex) {
              System.out.println("I/O Exception in getCanonicalPath");
              ex.printStackTrace();
            }

            //   extract the path specification of the generated Java class that implements the ODE
            // solution method,
            //    in order to update the ScalaSci class path
            String SelectedFileWithPath = f.getAbsolutePath();
            String SelectedFilePathOnly =
                SelectedFileWithPath.substring(
                    0, SelectedFileWithPath.lastIndexOf(File.separatorChar));

            if (GlobalValues.ScalaSciClassPath.length() == 0) GlobalValues.ScalaSciClassPath = ".";
            if (GlobalValues.ScalaSciClassPath.indexOf(SelectedFilePathOnly) == -1) {
              GlobalValues.ScalaSciClassPathComponents.add(0, SelectedFilePathOnly);
              GlobalValues.ScalaSciClassPath =
                  GlobalValues.ScalaSciClassPath + File.pathSeparator + SelectedFilePathOnly;
            }
            // update also the ScalaSciClassPath property
            StringBuilder fileStr = new StringBuilder();
            Enumeration enumDirs = GlobalValues.ScalaSciClassPathComponents.elements();
            while (enumDirs.hasMoreElements()) {
              Object ce = enumDirs.nextElement();
              fileStr.append(File.pathSeparator + (String) ce);
            }
            GlobalValues.settings.setProperty("ScalaSciClassPath", fileStr.toString());

            ClassLoader parentClassLoader = getClass().getClassLoader();
            GlobalValues.extensionClassLoader =
                new ExtensionClassLoader(GlobalValues.ScalaSciClassPath, parentClassLoader);

            // update GUI components to account for the updated ScalaSci classpath
            scalaExec.scalaLab.scalaLab.updateTree();

            String[] command = new String[11];
            String toolboxes = "";
            for (int k = 0; k < GlobalValues.ScalaSciClassPathComponents.size(); k++)
              toolboxes =
                  toolboxes
                      + File.pathSeparator
                      + GlobalValues.ScalaSciClassPathComponents.elementAt(k);

            // compile the temporary file
            command[0] = "java";
            command[1] = "-classpath";
            command[2] =
                "."
                    + File.pathSeparator
                    + GlobalValues.jarFilePath
                    + File.pathSeparator
                    + toolboxes
                    + File.pathSeparator
                    + SelectedFilePathOnly;
            command[3] = "com.sun.tools.javac.Main"; // the name of the Java  compiler class
            command[4] = "-classpath";
            command[5] = command[2];
            command[6] = "-sourcepath";
            command[7] = command[2];
            command[8] = "-d"; // where to place output class files
            command[9] = SelectedFilePathOnly;
            command[10] = SelectedFileWithPath;
            String compileCommandString =
                command[0]
                    + "  "
                    + command[1]
                    + "  "
                    + command[2]
                    + " "
                    + command[3]
                    + " "
                    + command[4]
                    + " "
                    + command[5]
                    + " "
                    + command[6]
                    + " "
                    + command[7]
                    + " "
                    + command[8]
                    + " "
                    + command[9]
                    + " "
                    + command[10];

            System.out.println("compileCommand Java= " + compileCommandString);

            try {
              Runtime rt = Runtime.getRuntime();
              Process javaProcess = rt.exec(command);
              // an error message?
              StreamGobbler errorGobbler = new StreamGobbler(javaProcess.getErrorStream(), "ERROR");

              // any output?
              StreamGobbler outputGobbler =
                  new StreamGobbler(javaProcess.getInputStream(), "OUTPUT");

              // kick them off
              errorGobbler.start();
              outputGobbler.start();

              // any error???
              javaProcess.waitFor();
              int rv = javaProcess.exitValue();
              if (rv == 0) {
                System.out.println("Process:  exited successfully ");

                JavaCompile javaCompileObj = null;
                try {
                  javaCompileObj = new JavaCompile();
                } catch (Exception ex) {
                  JOptionPane.showMessageDialog(
                      null,
                      "Unable to compile. Please check if your system's PATH variable includes the path to your javac compiler",
                      "Cannot compile - Check PATH",
                      JOptionPane.INFORMATION_MESSAGE);
                  ex.printStackTrace();
                }
                generateScriptCodeButton.setEnabled(true);
                statusAreaBottom.setText(
                    "Step5:  You can proceed now to create a draft ScalaSci-Script that utilizes your Java-based  ODE integrator");

              } else System.out.println("Process:  exited with error, error value = " + rv);

            } catch (IOException exio) {
              System.out.println("IOException trying to executing " + command);
              exio.printStackTrace();

            } catch (InterruptedException ie) {
              System.out.println("Interrupted Exception  trying to executing " + command);
              ie.printStackTrace();
            }
          }
        });

    // Step 5: Generate Script Code
    generateScriptCodeButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            new scriptCodeGenerationFrame("ODE Script code", editingClassName, systemOrder);
          }
        });

    buttonPanel.add(copyTemplateButton); // Step 1
    buttonPanel.setEnabled(true);
    buttonPanel.add(generateEditingButton); // Step 2
    generateEditingButton.setEnabled(false);
    buttonPanel.add(saveJavaClassButton); // Step 3
    saveJavaClassButton.setEnabled(false);
    buttonPanel.add(compileJavaClassButton); // Step 4
    buttonPanel.add(compileJavaInternalCompilerButton);
    compileJavaClassButton.setEnabled(false);
    compileJavaInternalCompilerButton.setEnabled(false);
    buttonPanel.add(generateScriptCodeButton); // Step 5
    generateScriptCodeButton.setEnabled(false);

    ODEWizardFrame.add(buttonPanel, BorderLayout.NORTH);
    ODEWizardFrame.add(editPanel, BorderLayout.CENTER);
    JPanel bottomPanel = new JPanel(new GridLayout(2, 1));

    bottomPanel.add(paramPanel);
    bottomPanel.add(statusPanel);
    ODEWizardFrame.add(bottomPanel, BorderLayout.SOUTH);
    ODEWizardFrame.setLocation(100, 100);
    ODEWizardFrame.setSize(1400, 800);
    ODEWizardFrame.setVisible(true);
  }
Example #10
0
  public TableModelDemo() {

    try {
      // Load the JDBC driver
      Class.forName("com.mysql.jdbc.Driver");
      Class.forName("oracle.jdbc.driver.OracleDriver");
      System.out.println("Driver loaded");

      // Create a row set
      rowSet = new CachedRowSetImpl();

      // Set RowSet properties
      //      rowSet.setUrl("jdbc:mysql://localhost/javabook");
      rowSet.setUrl("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl");
      rowSet.setUsername("scott");
      rowSet.setPassword("tiger");

      rowSet.setCommand("select * from StateCapital");

      rowSet.setConcurrency(ResultSet.CONCUR_UPDATABLE);
      rowSet.execute();
      tableModel.setRowSet(rowSet);
      rowSet.addRowSetListener(tableModel);
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    JPanel panel1 = new JPanel();
    panel1.setLayout(new GridLayout(2, 2));
    panel1.add(jbtAddRow);
    panel1.add(jbtAddColumn);
    panel1.add(jbtDeleteRow);
    panel1.add(jbtDeleteColumn);

    JPanel panel2 = new JPanel();
    panel2.add(jbtSave);
    panel2.add(jbtClear);
    panel2.add(jbtRestore);

    JPanel panel3 = new JPanel();
    panel3.setLayout(new BorderLayout(5, 0));
    panel3.add(new JLabel("Selection Mode"), BorderLayout.WEST);
    panel3.add(jcboSelectionMode, BorderLayout.CENTER);

    JPanel panel4 = new JPanel();
    panel4.setLayout(new FlowLayout(FlowLayout.LEFT));
    panel4.add(jchkRowSelectionAllowed);
    panel4.add(jchkColumnSelectionAllowed);

    JPanel panel5 = new JPanel();
    panel5.setLayout(new GridLayout(2, 1));
    panel5.add(panel3);
    panel5.add(panel4);

    JPanel panel6 = new JPanel();
    panel6.setLayout(new BorderLayout());
    panel6.add(panel1, BorderLayout.SOUTH);
    panel6.add(panel2, BorderLayout.CENTER);

    add(panel5, BorderLayout.NORTH);
    add(new JScrollPane(jTable1), BorderLayout.CENTER);
    add(panel6, BorderLayout.SOUTH);

    // Initialize table selection mode
    jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    jbtAddRow.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              rowSet.absolute(2);
              rowSet.moveToInsertRow();
              rowSet.updateString("state", "Georia");
              rowSet.updateString("capital", "Atlanta");
              rowSet.insertRow();
              ((CachedRowSetImpl) rowSet).acceptChanges();
              rowSet.moveToCurrentRow();
            } catch (Exception ex) {
              ex.printStackTrace();
            }

            //        if (jTable1.getSelectedRow() >= 0)
            //          tableModel.insertRow(jTable1.getSelectedRow(),
            //            new java.util.Vector());
            //        else
            //          tableModel.addRow(new java.util.Vector());
          }
        });

    jbtAddColumn.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            //        String name = JOptionPane.showInputDialog("New Column Name");
            //        tableModel.addColumn(name, new java.util.Vector());
          }
        });

    jbtDeleteRow.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            if (jTable1.getSelectedRow() >= 0) {
              try {
                rowSet.absolute(jTable1.getSelectedRow() + 1);
                rowSet.deleteRow();
                ((CachedRowSetImpl) rowSet).acceptChanges();
              } catch (Exception ex) {
                ex.printStackTrace();
              }
            }
          }
        });

    jbtDeleteColumn.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            if (jTable1.getSelectedColumn() >= 0) {
              TableColumnModel columnModel = jTable1.getColumnModel();
              TableColumn tableColumn = columnModel.getColumn(jTable1.getSelectedColumn());
              columnModel.removeColumn(tableColumn);
            }
          }
        });

    jbtSave.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              ObjectOutputStream out =
                  new ObjectOutputStream(new FileOutputStream("tablemodel.dat"));
              //          out.writeObject(tableModel.getDataVector());
              out.writeObject(getColumnNames());
              out.close();
            } catch (Exception ex) {
              ex.printStackTrace();
            }
          }
        });

    jbtClear.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            //        tableModel.setRowCount(0);
          }
        });

    jbtRestore.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              ObjectInputStream in = new ObjectInputStream(new FileInputStream("tablemodel.dat"));
              Vector rowData = (Vector) in.readObject();
              Vector columnNames = (Vector) in.readObject();
              //          tableModel.setDataVector(rowData, columnNames);
              in.close();
            } catch (Exception ex) {
              ex.printStackTrace();
            }
          }
        });

    jchkRowSelectionAllowed.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            jTable1.setRowSelectionAllowed(jchkRowSelectionAllowed.isSelected());
          }
        });

    jchkColumnSelectionAllowed.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            jTable1.setColumnSelectionAllowed(jchkColumnSelectionAllowed.isSelected());
          }
        });

    jcboSelectionMode.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            String selectedItem = (String) jcboSelectionMode.getSelectedItem();

            if (selectedItem.equals("SINGLE_SELECTION"))
              jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            else if (selectedItem.equals("SINGLE_INTERVAL_SELECTION"))
              jTable1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            else if (selectedItem.equals("MULTIPLE_INTERVAL_SELECTION"))
              jTable1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
          }
        });
  }
    private void refresh(int index) {
      GridBagConstraints c = new GridBagConstraints();

      // No connector ................
      if (acs.size() == 0) {
        add(new JLabel(bundle.getString("CTL_No_Connector")), c);
        return;
      }

      // Connector switch ................
      if (acs.size() > 1) {
        c.insets = new Insets(0, 0, 3, 3);
        add(new JLabel(bundle.getString("CTL_Connector")), c);

        cbConnectors = new JComboBox();
        int i, k = acs.size();
        for (i = 0; i < k; i++) {
          AttachingConnector ac = (AttachingConnector) acs.get(i);
          int jj = ac.name().lastIndexOf('.');
          String s = (jj < 0) ? ac.name() : ac.name().substring(jj + 1);
          cbConnectors.addItem(s + " (" + ac.description() + ")");
        }
        c = new GridBagConstraints();
        c.insets = new Insets(0, 3, 3, 0);
        c.weightx = 1.0;
        c.fill = java.awt.GridBagConstraints.HORIZONTAL;
        c.gridwidth = 0;
        cbConnectors.setSelectedIndex(index);
        cbConnectors.setActionCommand("SwitchMe!");
        cbConnectors.addActionListener(this);
        add(cbConnectors, c);
      }

      ac = (AttachingConnector) acs.get(index);

      // Transport ................
      c = new GridBagConstraints();
      c.insets = new Insets(3, 0, 0, 3);
      add(new JLabel(bundle.getString("CTL_Transport")), c);

      JTextField tfTransport = new JTextField(ac.transport().name());
      tfTransport.setEnabled(false);
      c = new GridBagConstraints();
      c.gridwidth = 0;
      c.insets = new Insets(3, 3, 0, 0);
      c.fill = java.awt.GridBagConstraints.HORIZONTAL;
      c.weightx = 1.0;
      add(tfTransport, c);

      // Other params ................
      args = ac.defaultArguments();
      tfParams = new JTextField[args.size()];
      Iterator it = args.keySet().iterator();
      int i = 0;
      while (it.hasNext()) {
        String name = (String) it.next();
        Argument a = (Argument) args.get(name);

        c = new GridBagConstraints();
        c.insets = new Insets(6, 0, 0, 3);
        c.anchor = GridBagConstraints.WEST;
        add(new JLabel(a.label() + ": "), c);

        JTextField tfParam = new JTextField(a.value());
        tfParams[i++] = tfParam;
        tfParam.setName(name);
        c = new GridBagConstraints();
        c.gridwidth = 0;
        c.insets = new Insets(6, 3, 0, 0);
        c.fill = java.awt.GridBagConstraints.HORIZONTAL;
        c.weightx = 1.0;
        add(tfParam, c);
      }

      c = new GridBagConstraints();
      c.weighty = 1.0;
      JPanel p = new JPanel();
      p.setPreferredSize(new Dimension(1, 1));
      add(p, c);
    }
    /** Create the UI for this editor */
    void makeUI() {

      JPanel mainPanel = new JPanel(new BorderLayout());
      mainPanel.setBorder(new LineBorder(Color.blue));
      getContentPane().add(mainPanel, BorderLayout.CENTER);

      // the map and associated toolbar
      npEditControl = new NPController();
      mapEditPanel = npEditControl.getNavigatedPanel(); // here's where the map will be drawn
      mapEditPanel.setPreferredSize(new Dimension(250, 250));
      mapEditPanel.setSelectRegionMode(true);
      JToolBar navToolbar = mapEditPanel.getNavToolBar();
      navToolbar.setFloatable(false);
      JToolBar moveToolbar = mapEditPanel.getMoveToolBar();
      moveToolbar.setFloatable(false);
      // toolbar.remove("setReference");

      JPanel toolbar = new JPanel();
      List localMaps = maps;
      if (localMaps == null) {
        localMaps = getDefaultMaps();
      }
      JMenu mapMenu = new JMenu("Maps");
      JMenuBar menuHolder = new JMenuBar();
      menuHolder.setBorder(null);
      menuHolder.add(mapMenu);
      toolbar.add(menuHolder);
      for (int mapIdx = 0; mapIdx < localMaps.size(); mapIdx++) {
        final MapData mapData = (MapData) localMaps.get(mapIdx);
        final JCheckBoxMenuItem cbx =
            new JCheckBoxMenuItem(mapData.getDescription(), mapData.getVisible());
        if (mapData.getVisible()) {
          toggleMap(mapData, true);
        }
        mapMenu.add(cbx);
        cbx.addItemListener(
            new ItemListener() {
              public void itemStateChanged(ItemEvent event) {
                toggleMap(mapData, cbx.isSelected());
              }
            });
      }
      GuiUtils.limitMenuSize(mapMenu, "Maps ", 20);

      toolbar.add(navToolbar);
      toolbar.add(moveToolbar);

      JPanel mapSide = new JPanel();
      mapSide.setLayout(new BorderLayout());
      TitledBorder mapBorder =
          new TitledBorder(
              standardBorder, "Edit Projection", TitledBorder.ABOVE_TOP, TitledBorder.CENTER);
      mapSide.setBorder(mapBorder);
      mapSide.add(toolbar, BorderLayout.NORTH);
      mapSide.add(mapEditPanel, BorderLayout.CENTER);
      mainPanel.add(mapSide, BorderLayout.WEST);

      // the projection parameters

      // the Projection name
      JLabel nameLabel = GuiUtils.rLabel("Name: ");
      nameTF = new JTextField(20);

      // the list of Projection classes is kept in a comboBox
      typeLabel = GuiUtils.rLabel("Type: ");
      projClassCB = new JComboBox();
      // standard list of projection classes
      List classNames = getDefaultProjections();
      for (int i = 0; i < classNames.size(); i++) {
        String className = (String) classNames.get(i);
        try {
          projClassCB.addItem(new ProjectionClass(className));
        } catch (ClassNotFoundException ee) {
          System.err.println("ProjectionManager failed on " + className + " " + ee);
        } catch (IntrospectionException ee) {
          System.err.println("ProjectionManager failed on " + className + " " + ee);
        }
      }
      GuiUtils.tmpInsets = new Insets(4, 4, 4, 4);
      JPanel topPanel =
          GuiUtils.doLayout(
              new Component[] {nameLabel, nameTF, typeLabel, projClassCB},
              2,
              GuiUtils.WT_N,
              GuiUtils.WT_N);

      // the Projection parameter area
      paramPanel = new JPanel();
      paramPanel.setLayout(new BorderLayout());
      paramPanel.setBorder(
          new TitledBorder(
              standardBorder,
              "Projection Parameters",
              TitledBorder.ABOVE_TOP,
              TitledBorder.CENTER));

      // the bottom button panel
      JPanel buttPanel = new JPanel();
      JButton acceptButton = new JButton("Save");
      JButton previewButton = new JButton("Preview");
      JButton cancelButton = new JButton("Cancel");
      buttPanel.add(acceptButton, null);
      buttPanel.add(previewButton, null);
      buttPanel.add(cancelButton, null);

      JPanel mainBox = GuiUtils.topCenterBottom(topPanel, paramPanel, buttPanel);
      mainPanel.add(mainBox, BorderLayout.CENTER);
      pack();

      // enable event listeners when we're done constructing the UI
      projClassCB.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              ProjectionClass selectClass = (ProjectionClass) projClassCB.getSelectedItem();
              setProjection(selectClass.makeDefaultProjection());
            }
          });

      acceptButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              accept();
            }
          });
      previewButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              ProjectionClass projClass = findProjectionClass(editProjection);
              if (null != projClass) {
                setProjFromDialog(projClass, editProjection);
                setProjection(editProjection);
              }
            }
          });
      cancelButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              NewProjectionDialog.this.setVisible(false);
            }
          });
    }
Example #13
0
  public DownloadPictures(ArrayList<CardDownloadData> cards) {
    this.cards = cards;

    bar = new JProgressBar(this);

    JPanel p0 = new JPanel();
    p0.setLayout(new BoxLayout(p0, BoxLayout.Y_AXIS));

    p0.add(Box.createVerticalStrut(5));
    jLabel1 = new JLabel();
    jLabel1.setText("Please select server:");

    jLabel1.setAlignmentX(Component.LEFT_ALIGNMENT);

    p0.add(jLabel1);
    p0.add(Box.createVerticalStrut(5));
    ComboBoxModel jComboBox1Model =
        new DefaultComboBoxModel(
            new String[] {
              "magiccards.info",
              "wizards.com",
              "mtgimage.com (HQ)" /*, "mtgathering.ru HQ", "mtgathering.ru MQ", "mtgathering.ru LQ"*/
            });
    jComboBox1 = new JComboBox();

    cardImageSource = MagicCardsImageSource.getInstance();

    jComboBox1.setModel(jComboBox1Model);
    jComboBox1.setAlignmentX(Component.LEFT_ALIGNMENT);
    jComboBox1.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JComboBox cb = (JComboBox) e.getSource();
            switch (cb.getSelectedIndex()) {
              case 0:
                cardImageSource = MagicCardsImageSource.getInstance();
                break;
              case 1:
                cardImageSource = WizardCardsImageSource.getInstance();
                break;
              case 2:
                cardImageSource = MtgImageSource.getInstance();
                break;
            }
            int count = DownloadPictures.this.cards.size();
            float mb = (count * cardImageSource.getAverageSize()) / 1024;
            bar.setString(
                String.format(
                    cardIndex == count
                        ? "%d of %d cards finished! Please close!"
                        : "%d of %d cards finished! Please wait! [%.1f Mb]",
                    0,
                    count,
                    mb));
          }
        });
    p0.add(jComboBox1);
    p0.add(Box.createVerticalStrut(5));

    // Start
    startDownloadButton = new JButton("Start download");
    startDownloadButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            new Thread(DownloadPictures.this).start();
            startDownloadButton.setEnabled(false);
            checkBox.setEnabled(false);
          }
        });
    p0.add(Box.createVerticalStrut(5));

    // Progress
    p0.add(bar);
    bar.setStringPainted(true);
    int count = cards.size();
    float mb = (count * cardImageSource.getAverageSize()) / 1024;
    bar.setString(
        String.format(
            cardIndex == cards.size()
                ? "%d of %d cards finished! Please close!"
                : "%d of %d cards finished! Please wait! [%.1f Mb]",
            0,
            cards.size(),
            mb));
    Dimension d = bar.getPreferredSize();
    d.width = 300;
    bar.setPreferredSize(d);

    p0.add(Box.createVerticalStrut(5));
    checkBox = new JCheckBox("Download images for Standard (Type2) only");
    p0.add(checkBox);
    p0.add(Box.createVerticalStrut(5));

    checkBox.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            ArrayList<CardDownloadData> cardsToDownload = DownloadPictures.this.cards;
            if (checkBox.isSelected()) {
              DownloadPictures.this.type2cards = new ArrayList<>();
              for (CardDownloadData data : DownloadPictures.this.cards) {
                if (data.isType2() || data.isToken()) {
                  DownloadPictures.this.type2cards.add(data);
                }
              }
              cardsToDownload = DownloadPictures.this.type2cards;
            }
            int count = cardsToDownload.size();
            float mb = (count * cardImageSource.getAverageSize()) / 1024;
            bar.setString(
                String.format(
                    cardIndex == count
                        ? "%d of %d cards finished! Please close!"
                        : "%d of %d cards finished! Please wait! [%.1f Mb]",
                    0,
                    count,
                    mb));
          }
        });

    // JOptionPane
    Object[] options = {startDownloadButton, closeButton = new JButton("Cancel")};
    dlg =
        new JOptionPane(
            p0, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[1]);
  }
Example #14
0
  public SceneLayoutApp() {
    super();
    new Pair();
    final JFrame frame = new JFrame("Scene Layout");

    final JPanel panel = new JPanel(new BorderLayout());
    frame.setContentPane(panel);
    final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setMaximumSize(screenSize);
    frame.setSize(screenSize);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JMenuBar mb = new JMenuBar();
    frame.setJMenuBar(mb);

    final JMenu jMenu = new JMenu("File");
    mb.add(jMenu);
    mb.add(new JMenu("Edit"));
    mb.add(new JMenu("Help"));
    JMenu menu = new JMenu("Look and Feel");

    //
    // Get all the available look and feel that we are going to use for
    // creating the JMenuItem and assign the action listener to handle
    // the selection of menu item to change the look and feel.
    //
    UIManager.LookAndFeelInfo[] lookAndFeelInfos = UIManager.getInstalledLookAndFeels();
    for (int i = 0; i < lookAndFeelInfos.length; i++) {
      final UIManager.LookAndFeelInfo lookAndFeelInfo = lookAndFeelInfos[i];
      JMenuItem item = new JMenuItem(lookAndFeelInfo.getName());
      item.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              try {
                //
                // Set the look and feel for the frame and update the UI
                // to use a new selected look and feel.
                //
                UIManager.setLookAndFeel(lookAndFeelInfo.getClassName());
                SwingUtilities.updateComponentTreeUI(frame);
              } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
              } catch (InstantiationException e1) {
                e1.printStackTrace();
              } catch (IllegalAccessException e1) {
                e1.printStackTrace();
              } catch (UnsupportedLookAndFeelException e1) {
                e1.printStackTrace();
              }
            }
          });
      menu.add(item);
    }

    mb.add(menu);
    jMenu.add(new JMenuItem(new scene.action.QuitAction()));

    panel.add(new JScrollPane(desktopPane), BorderLayout.CENTER);
    final JToolBar bar = new JToolBar();

    panel.add(bar, BorderLayout.NORTH);

    final JComboBox comboNewWindow =
        new JComboBox(
            new String[] {"320:180", "320:240", "640:360", "640:480", "1280:720", "1920:1080"});

    comboNewWindow.addActionListener(new CreateSceneWindowAction());

    comboNewWindow.setBorder(BorderFactory.createTitledBorder("Create New Window"));
    bar.add(comboNewWindow);
    bar.add(
        new AbstractAction("Progress Bars") {

          /** Invoked when an action occurs. */
          @Override
          public void actionPerformed(ActionEvent e) {
            new ProgressBarAnimator();
          }
        });
    bar.add(
        new AbstractAction("Sliders") {

          /** Invoked when an action occurs. */
          @Override
          public void actionPerformed(ActionEvent e) {
            new SliderBarAnimator();
          }
        });

    final JCheckBox permaViz = new JCheckBox();
    permaViz.setText("Show the dump window");
    permaViz.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));

    dumpWindow = new JInternalFrame("perma dump window");
    dumpWindow.setContentPane(new JScrollPane(permText));

    permaViz.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            dumpWindow.setVisible(permaViz.isSelected());
          }
        });

    comboNewWindow.setMaximumSize(comboNewWindow.getPreferredSize());

    permaViz.setSelected(false);
    bar.add(new CreateWebViewV1Action());
    bar.add(new CreateWebViewV2Action());
    bar.add(permaViz);
    desktopPane.add(dumpWindow);
    dumpWindow.setSize(400, 400);
    dumpWindow.setResizable(true);
    dumpWindow.setClosable(false);
    dumpWindow.setIconifiable(false);
    final JMenuBar m = new JMenuBar();
    final JMenu cmenu = new JMenu("Create");
    m.add(cmenu);
    final JMenuItem menuItem =
        new JMenuItem(
            new AbstractAction("new") {
              @Override
              public void actionPerformed(ActionEvent e) {
                Runnable runnable =
                    new Runnable() {
                      public void run() {
                        Object[] in = (Object[]) XSTREAM.fromXML(permText.getText());

                        final JInternalFrame ff = new JInternalFrame();

                        final ScenePanel c = new ScenePanel();
                        ff.setContentPane(c);
                        desktopPane.add(ff);
                        final Dimension d = (Dimension) in[0];
                        c.setMaximumSize(d);
                        c.setPreferredSize(d);

                        ff.setSize(d.width + 50, d.height + 50);
                        ScenePanel.panes.put(c, (List<Pair<Point, ArrayList<URL>>>) in[1]);

                        c.invalidate();
                        c.repaint();

                        ff.pack();
                        ff.setClosable(true);

                        ff.setMaximizable(false);
                        ff.setIconifiable(false);
                        ff.setResizable(false);
                        ff.show();
                      }
                    };

                SwingUtilities.invokeLater(runnable);
              }
            });
    cmenu.add(menuItem);
    //        JMenuBar menuBar = new JMenuBar();

    //        getContentPane().add(menuBar);

    dumpWindow.setJMenuBar(m);
    frame.setVisible(true);
  }
Example #15
0
  /**
   * Create preview component.
   *
   * @param comboBox the options.
   * @return the component.
   */
  private static Component createPreview(final JComboBox comboBox) {
    final JComponent preview;

    JLabel noPreview =
        new JLabel(GuiActivator.getResources().getI18NString("impl.media.configform.NO_PREVIEW"));
    noPreview.setHorizontalAlignment(SwingConstants.CENTER);
    noPreview.setVerticalAlignment(SwingConstants.CENTER);

    preview = createVideoContainer(noPreview);

    preview.setPreferredSize(new Dimension(WIDTH, 280));
    preview.setMaximumSize(new Dimension(WIDTH, 280));

    final ActionListener comboBoxListener =
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            MediaDevice device = (MediaDevice) comboBox.getSelectedItem();

            if ((device != null) && device.equals(videoDeviceInPreview)) return;

            Exception exception;
            try {
              createPreview(device, preview);
              exception = null;
            } catch (IOException ex) {
              exception = ex;
            } catch (MediaException ex) {
              exception = ex;
            }
            if (exception != null) {
              logger.error("Failed to create preview for device " + device, exception);

              device = null;
            }

            videoDeviceInPreview = device;
          }
        };
    comboBox.addActionListener(comboBoxListener);

    /*
     * We have to initialize the controls to reflect the configuration
     * at the time of creating this instance. Additionally, because the
     * video preview will stop when it and its associated controls
     * become unnecessary, we have to restart it when the mentioned
     * controls become necessary again. We'll address the two goals
     * described by pretending there's a selection in the video combo
     * box when the combo box in question becomes displayable.
     */
    comboBox.addHierarchyListener(
        new HierarchyListener() {
          public void hierarchyChanged(HierarchyEvent event) {
            if (((event.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0)
                && comboBox.isDisplayable()) {
              // let current changes end their execution
              // and after that trigger action on combobox
              SwingUtilities.invokeLater(
                  new Runnable() {
                    public void run() {
                      comboBoxListener.actionPerformed(null);
                    }
                  });
            } else {
              if (!comboBox.isDisplayable()) videoDeviceInPreview = null;
            }
          }
        });

    return preview;
  }
Example #16
0
  /**
   * Creates the video advanced settings.
   *
   * @return video advanced settings panel.
   */
  private static Component createVideoAdvancedSettings() {
    ResourceManagementService resources = NeomediaActivator.getResources();

    final DeviceConfiguration deviceConfig = mediaService.getDeviceConfiguration();

    TransparentPanel centerPanel = new TransparentPanel(new GridBagLayout());
    centerPanel.setMaximumSize(new Dimension(WIDTH, 150));

    JButton resetDefaultsButton =
        new JButton(resources.getI18NString("impl.media.configform.VIDEO_RESET"));
    JPanel resetButtonPanel = new TransparentPanel(new FlowLayout(FlowLayout.RIGHT));
    resetButtonPanel.add(resetDefaultsButton);

    final JPanel centerAdvancedPanel = new TransparentPanel(new BorderLayout());
    centerAdvancedPanel.add(centerPanel, BorderLayout.NORTH);
    centerAdvancedPanel.add(resetButtonPanel, BorderLayout.SOUTH);

    GridBagConstraints constraints = new GridBagConstraints();
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.anchor = GridBagConstraints.NORTHWEST;
    constraints.insets = new Insets(5, 5, 0, 0);
    constraints.gridx = 0;
    constraints.weightx = 0;
    constraints.weighty = 0;
    constraints.gridy = 0;

    centerPanel.add(
        new JLabel(resources.getI18NString("impl.media.configform.VIDEO_RESOLUTION")), constraints);
    constraints.gridy = 1;
    constraints.insets = new Insets(0, 0, 0, 0);
    final JCheckBox frameRateCheck =
        new SIPCommCheckBox(resources.getI18NString("impl.media.configform.VIDEO_FRAME_RATE"));
    centerPanel.add(frameRateCheck, constraints);
    constraints.gridy = 2;
    constraints.insets = new Insets(5, 5, 0, 0);
    centerPanel.add(
        new JLabel(resources.getI18NString("impl.media.configform.VIDEO_PACKETS_POLICY")),
        constraints);

    constraints.weightx = 1;
    constraints.gridx = 1;
    constraints.gridy = 0;
    constraints.insets = new Insets(5, 0, 0, 5);
    Object[] resolutionValues = new Object[DeviceConfiguration.SUPPORTED_RESOLUTIONS.length + 1];
    System.arraycopy(
        DeviceConfiguration.SUPPORTED_RESOLUTIONS,
        0,
        resolutionValues,
        1,
        DeviceConfiguration.SUPPORTED_RESOLUTIONS.length);
    final JComboBox sizeCombo = new JComboBox(resolutionValues);
    sizeCombo.setRenderer(new ResolutionCellRenderer());
    sizeCombo.setEditable(false);
    centerPanel.add(sizeCombo, constraints);

    // default value is 20
    final JSpinner frameRate = new JSpinner(new SpinnerNumberModel(20, 5, 30, 1));
    frameRate.addChangeListener(
        new ChangeListener() {
          public void stateChanged(ChangeEvent e) {
            deviceConfig.setFrameRate(
                ((SpinnerNumberModel) frameRate.getModel()).getNumber().intValue());
          }
        });
    constraints.gridy = 1;
    constraints.insets = new Insets(0, 0, 0, 5);
    centerPanel.add(frameRate, constraints);

    frameRateCheck.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (frameRateCheck.isSelected()) {
              deviceConfig.setFrameRate(
                  ((SpinnerNumberModel) frameRate.getModel()).getNumber().intValue());
            } else // unlimited framerate
            deviceConfig.setFrameRate(-1);

            frameRate.setEnabled(frameRateCheck.isSelected());
          }
        });

    final JSpinner videoMaxBandwidth =
        new JSpinner(
            new SpinnerNumberModel(deviceConfig.getVideoMaxBandwidth(), 1, Integer.MAX_VALUE, 1));
    videoMaxBandwidth.addChangeListener(
        new ChangeListener() {
          public void stateChanged(ChangeEvent e) {
            deviceConfig.setVideoMaxBandwidth(
                ((SpinnerNumberModel) videoMaxBandwidth.getModel()).getNumber().intValue());
          }
        });
    constraints.gridx = 1;
    constraints.gridy = 2;
    constraints.insets = new Insets(0, 0, 5, 5);
    centerPanel.add(videoMaxBandwidth, constraints);

    resetDefaultsButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // reset to defaults
            sizeCombo.setSelectedIndex(0);
            frameRateCheck.setSelected(false);
            frameRate.setEnabled(false);
            frameRate.setValue(20);
            // unlimited framerate
            deviceConfig.setFrameRate(-1);
            videoMaxBandwidth.setValue(DeviceConfiguration.DEFAULT_VIDEO_MAX_BANDWIDTH);
          }
        });

    // load selected value or auto
    Dimension videoSize = deviceConfig.getVideoSize();

    if ((videoSize.getHeight() != DeviceConfiguration.DEFAULT_VIDEO_HEIGHT)
        && (videoSize.getWidth() != DeviceConfiguration.DEFAULT_VIDEO_WIDTH))
      sizeCombo.setSelectedItem(deviceConfig.getVideoSize());
    else sizeCombo.setSelectedIndex(0);
    sizeCombo.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Dimension selectedVideoSize = (Dimension) sizeCombo.getSelectedItem();

            if (selectedVideoSize == null) {
              // the auto value, default one
              selectedVideoSize =
                  new Dimension(
                      DeviceConfiguration.DEFAULT_VIDEO_WIDTH,
                      DeviceConfiguration.DEFAULT_VIDEO_HEIGHT);
            }
            deviceConfig.setVideoSize(selectedVideoSize);
          }
        });

    frameRateCheck.setSelected(
        deviceConfig.getFrameRate() != DeviceConfiguration.DEFAULT_VIDEO_FRAMERATE);
    frameRate.setEnabled(frameRateCheck.isSelected());

    if (frameRate.isEnabled()) frameRate.setValue(deviceConfig.getFrameRate());

    return centerAdvancedPanel;
  }
Example #17
0
  private static void createAudioPreview(
      final AudioSystem audioSystem,
      final JComboBox comboBox,
      final SoundLevelIndicator soundLevelIndicator) {
    final ActionListener captureComboActionListener =
        new ActionListener() {
          private final SimpleAudioLevelListener audioLevelListener =
              new SimpleAudioLevelListener() {
                public void audioLevelChanged(int level) {
                  soundLevelIndicator.updateSoundLevel(level);
                }
              };

          private AudioMediaDeviceSession deviceSession;

          private final BufferTransferHandler transferHandler =
              new BufferTransferHandler() {
                public void transferData(PushBufferStream stream) {
                  try {
                    stream.read(transferHandlerBuffer);
                  } catch (IOException ioe) {
                  }
                }
              };

          private final Buffer transferHandlerBuffer = new Buffer();

          public void actionPerformed(ActionEvent event) {
            setDeviceSession(null);

            CaptureDeviceInfo cdi;

            if (comboBox == null) {
              cdi = soundLevelIndicator.isShowing() ? audioSystem.getCaptureDevice() : null;
            } else {
              Object selectedItem =
                  soundLevelIndicator.isShowing() ? comboBox.getSelectedItem() : null;

              cdi =
                  (selectedItem instanceof DeviceConfigurationComboBoxModel.CaptureDevice)
                      ? ((DeviceConfigurationComboBoxModel.CaptureDevice) selectedItem).info
                      : null;
            }

            if (cdi != null) {
              for (MediaDevice md : mediaService.getDevices(MediaType.AUDIO, MediaUseCase.ANY)) {
                if (md instanceof AudioMediaDeviceImpl) {
                  AudioMediaDeviceImpl amd = (AudioMediaDeviceImpl) md;

                  if (cdi.equals(amd.getCaptureDeviceInfo())) {
                    try {
                      MediaDeviceSession deviceSession = amd.createSession();
                      boolean setDeviceSession = false;

                      try {
                        if (deviceSession instanceof AudioMediaDeviceSession) {
                          setDeviceSession((AudioMediaDeviceSession) deviceSession);
                          setDeviceSession = true;
                        }
                      } finally {
                        if (!setDeviceSession) deviceSession.close();
                      }
                    } catch (Throwable t) {
                      if (t instanceof ThreadDeath) throw (ThreadDeath) t;
                    }
                    break;
                  }
                }
              }
            }
          }

          private void setDeviceSession(AudioMediaDeviceSession deviceSession) {
            if (this.deviceSession == deviceSession) return;

            if (this.deviceSession != null) {
              try {
                this.deviceSession.close();
              } finally {
                this.deviceSession.setLocalUserAudioLevelListener(null);
                soundLevelIndicator.resetSoundLevel();
              }
            }

            this.deviceSession = deviceSession;

            if (this.deviceSession != null) {
              this.deviceSession.setContentDescriptor(new ContentDescriptor(ContentDescriptor.RAW));
              this.deviceSession.setLocalUserAudioLevelListener(audioLevelListener);
              this.deviceSession.start(MediaDirection.SENDONLY);

              try {
                DataSource dataSource = this.deviceSession.getOutputDataSource();

                dataSource.connect();

                PushBufferStream[] streams = ((PushBufferDataSource) dataSource).getStreams();

                for (PushBufferStream stream : streams) stream.setTransferHandler(transferHandler);

                dataSource.start();
              } catch (Throwable t) {
                if (t instanceof ThreadDeath) throw (ThreadDeath) t;
                else setDeviceSession(null);
              }
            }
          }
        };

    if (comboBox != null) comboBox.addActionListener(captureComboActionListener);

    soundLevelIndicator.addHierarchyListener(
        new HierarchyListener() {
          public void hierarchyChanged(HierarchyEvent event) {
            if ((event.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
              SwingUtilities.invokeLater(
                  new Runnable() {
                    public void run() {
                      captureComboActionListener.actionPerformed(null);
                    }
                  });
            }
          }
        });
  }
Example #18
0
  public Viewer() {
    leveldbStore.setMultiSelectionEnabled(false);
    leveldbStore.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    putButton.setEnabled(false);
    key.setEnabled(false);
    value.setEnabled(false);
    findField.setEnabled(false);
    deleteButton.setEnabled(false);
    saveButton.setEnabled(false);
    putType.setEnabled(false);
    putType.setEditable(false);
    signedBox.setEnabled(false);

    openButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            if (openButton.isEnabled()) {
              openButton.setEnabled(false);
              new Thread() {
                public void run() {
                  if (leveldbStore.showOpenDialog(pane) == JFileChooser.APPROVE_OPTION) {
                    File select = leveldbStore.getSelectedFile();
                    if (select.isDirectory()) {
                      new OpenLevelDBDialog(Viewer.this, select);
                      openDatabase(select);
                      dbPathField.setText(select.getAbsolutePath());
                    } else {
                      JOptionPane.showMessageDialog(
                          pane,
                          "The selecting item must be a directory",
                          "Unable to load database",
                          JOptionPane.WARNING_MESSAGE);
                    }
                  } else {
                    openButton.setEnabled(true);
                  }
                }
              }.start();
            }
          }
        });

    deleteButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            if (dataList.getSelectedValue() != null) {
              delete(dataList.getSelectedValue().key);
            }
            openDatabase(leveldbStore.getSelectedFile());
          }
        });

    putButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            put(
                ((PutType) putType.getSelectedItem()).getBytes(key.getText()),
                ((PutType) putType.getSelectedItem()).getBytes(value.getText()));
            openDatabase(leveldbStore.getSelectedFile());
          }
        });

    findField.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            openDatabase(leveldbStore.getSelectedFile());
          }
        });
    findField
        .getDocument()
        .addDocumentListener(
            new DocumentListener() {
              @Override
              public void insertUpdate(DocumentEvent e) {
                openDatabase(leveldbStore.getSelectedFile());
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                openDatabase(leveldbStore.getSelectedFile());
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                openDatabase(leveldbStore.getSelectedFile());
              }
            });
    findField
        .getDocument()
        .addUndoableEditListener(
            new UndoableEditListener() {
              @Override
              public void undoableEditHappened(UndoableEditEvent e) {
                openDatabase(leveldbStore.getSelectedFile());
              }
            });

    hexKey
        .getDocument()
        .addDocumentListener(
            new DocumentListener() {
              @Override
              public void insertUpdate(DocumentEvent e) {
                update(hexKey);
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                update(hexKey);
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                update(hexKey);
              }
            });
    hexKey
        .getDocument()
        .addUndoableEditListener(
            new UndoableEditListener() {
              @Override
              public void undoableEditHappened(UndoableEditEvent e) {
                update(hexKey);
              }
            });

    stringKey
        .getDocument()
        .addDocumentListener(
            new DocumentListener() {
              @Override
              public void insertUpdate(DocumentEvent e) {
                update(stringKey);
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                update(stringKey);
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                update(stringKey);
              }
            });
    stringKey
        .getDocument()
        .addUndoableEditListener(
            new UndoableEditListener() {
              @Override
              public void undoableEditHappened(UndoableEditEvent e) {
                update(stringKey);
              }
            });

    hexValue
        .getDocument()
        .addDocumentListener(
            new DocumentListener() {
              @Override
              public void insertUpdate(DocumentEvent e) {
                update(hexValue);
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                update(hexValue);
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                update(hexValue);
              }
            });
    hexValue
        .getDocument()
        .addUndoableEditListener(
            new UndoableEditListener() {
              @Override
              public void undoableEditHappened(UndoableEditEvent e) {
                update(hexValue);
              }
            });

    stringValue
        .getDocument()
        .addDocumentListener(
            new DocumentListener() {
              @Override
              public void insertUpdate(DocumentEvent e) {
                update(stringValue);
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                update(stringValue);
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                update(stringValue);
              }
            });
    stringValue
        .getDocument()
        .addUndoableEditListener(
            new UndoableEditListener() {
              @Override
              public void undoableEditHappened(UndoableEditEvent e) {
                update(stringValue);
              }
            });

    saveButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            save();
            openDatabase(leveldbStore.getSelectedFile());
          }
        });

    dataList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    dataList.addListSelectionListener(
        new ListSelectionListener() {
          @Override
          public void valueChanged(ListSelectionEvent e) {
            DBItem item = dataList.getSelectedValue();
            if (item != null) {
              hexValue.setText(cutToLine(LevelDBViewer.toHexString(item.value), 64));
              stringValue.setText(cutToLine(new String(item.value), 64));
              hexKey.setText(cutToLine(LevelDBViewer.toHexString(item.key), 64));
              stringKey.setText(cutToLine(new String(item.key), 64));

              lengthLabel.setText(String.valueOf(item.value.length + item.key.length));
              keyLength.setText(String.valueOf(item.key.length));
              valueLength.setText(String.valueOf(item.value.length));
            }
          }
        });

    signedBox.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            LevelDBViewer.DEFAULT_SINGED = signedBox.isSelected();
            int i = dataList.getSelectedIndex();
            dataList.clearSelection();
            dataList.updateUI();
            dataList.setSelectedIndex(i);
            update(hexKey);
            update(hexValue);
          }
        });

    for (PutType t : PutType.values()) {
      putType.addItem(t);
    }
    putType.setSelectedItem(PutType.STRING);
    putType.addItemListener(
        new ItemListener() {
          @Override
          public void itemStateChanged(ItemEvent e) {
            openDatabase(leveldbStore.getSelectedFile());
          }
        });
    putType.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            openDatabase(leveldbStore.getSelectedFile());
          }
        });

    dialog.setLocationByPlatform(true);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setContentPane(pane);
    dialog.setTitle("LevelDB Viewer By Marcus (https://github.com/SuperMarcus)");
    dialog.getRootPane().setDefaultButton(openButton);
    dialog.pack();
    dialog.setVisible(true);
  }