public BallsFrame() throws HeadlessException {
   super("Funny balls");
   setLayout(new BorderLayout());
   executorService = Executors.newScheduledThreadPool(1);
   ballsPanel =
       new JPanel() {
         @Override
         protected void paintComponent(Graphics g) {
           super.paintComponent(g);
           if (blueBallVisible) {
             g.setColor(Color.BLUE);
             g.fillOval(blueBall.x, getHeight() / 2, BALL_DIAGONAL, BALL_DIAGONAL);
           }
           g.setColor(Color.RED);
           g.fillOval(redBall.x, getHeight() / 2, BALL_DIAGONAL, BALL_DIAGONAL);
         }
       };
   add(ballsPanel, BorderLayout.CENTER);
   blueBallSwitch = new JCheckBox("Collision", true);
   blueBallSwitch.addItemListener(
       e -> {
         if (blueBallVisible = blueBallSwitch.isSelected()) {
           int x;
           do x = random.nextInt(getWidth() - BALL_DIAGONAL);
           while (redBall.x <= x && x <= redBall.rightX()
               || redBall.x <= x + BALL_DIAGONAL && x + BALL_DIAGONAL <= redBall.rightX());
           blueBall.x = x;
         }
       });
   add(blueBallSwitch, BorderLayout.SOUTH);
   blueBallVisible = true;
   moveToRight = true;
   setSize(500, 500);
 }
Esempio n. 2
0
  public MixingColors() {
    super("Selecting a color");
    contents = getContentPane();
    contents.setLayout(new FlowLayout());

    red = new JCheckBox("red");
    green = new JCheckBox("green");
    blue = new JCheckBox("blue");

    label = new JLabel("Watch my background");
    label.setOpaque(true);
    label.setForeground(Color.GRAY);
    label.setBackground(new Color(0, 0, 0));

    contents.add(red);
    contents.add(green);
    contents.add(blue);
    contents.add(label);

    // create CheckBoxHandler event handler
    // and register it on the checkboxes
    CheckBoxHandler cbh = new CheckBoxHandler();
    red.addItemListener(cbh);
    green.addItemListener(cbh);
    blue.addItemListener(cbh);

    setSize(225, 200);
    setVisible(true);
  }
Esempio n. 3
0
  public JComponent CreateOpTab(
      String operatorName, Map<String, Object> parameterMap, AppContext appContext) {

    initializeOperatorUI(operatorName, parameterMap);
    final JComponent panel = createPanel();

    bandList.addListSelectionListener(
        new ListSelectionListener() {
          public void valueChanged(final ListSelectionEvent e) {
            setNumberOfEigenvalues();
          }
        });

    showEigenvalues.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            showEigenvaluesFlag = (e.getStateChange() == ItemEvent.SELECTED);
          }
        });

    subtractMeanImage.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            subtractMeanImageFlag = (e.getStateChange() == ItemEvent.SELECTED);
          }
        });

    initParameters();

    return panel;
  }
Esempio n. 4
0
  @SuppressWarnings({"unchecked"})
  public SimulationPanel(final MainFrame frame, final PartitionDataList dataList) {

    this.frame = frame;
    this.dataList = dataList;

    optionPanel = new OptionsPanel(12, 12, SwingConstants.CENTER);

    simulationsNumberField = new WholeNumberField(1, Integer.MAX_VALUE);
    simulationsNumberField.setColumns(10);
    simulationsNumberField.setValue(dataList.simulationsCount);
    optionPanel.addComponentWithLabel("Number of simulations:", simulationsNumberField);

    setSeed = new JCheckBox();
    setSeed.addItemListener(new SetSeedCheckBoxListener());
    setSeed.setSelected(dataList.setSeed);
    optionPanel.addComponentWithLabel("Set seed:", setSeed);

    startingSeedNumberField = new WholeNumberField(1, Long.MAX_VALUE);
    startingSeedNumberField.setColumns(10);
    startingSeedNumberField.setValue(dataList.startingSeed);
    startingSeedNumberField.setEnabled(dataList.setSeed);
    optionPanel.addComponentWithLabel("Starting seed:", startingSeedNumberField);

    outputFormat = new JComboBox();
    optionPanel.addComponentWithLabel("Output format:", outputFormat);
    outputFormatModel = new DefaultComboBoxModel(SimpleAlignment.OutputType.values());
    outputFormat.setModel(outputFormatModel);

    outputAncestralSequences = new JCheckBox();
    outputAncestralSequences.addItemListener(new outputAncestralSequencesCheckBoxListener());
    outputAncestralSequences.setSelected(dataList.useParallel);
    optionPanel.addComponentWithLabel("Output ancestral sequences:", outputAncestralSequences);

    useParallel = new JCheckBox();
    useParallel.addItemListener(new UseParallelCheckBoxListener());
    useParallel.setSelected(dataList.useParallel);
    optionPanel.addComponentWithLabel("Use parallel implementation:", useParallel);

    // Buttons holder
    JPanel buttonsHolder = new JPanel();
    buttonsHolder.setOpaque(false);

    // simulate button
    simulate = new JButton("Simulate", Utils.createImageIcon(Utils.BIOHAZARD_ICON));
    simulate.addActionListener(new ListenSimulate());
    buttonsHolder.add(simulate);

    generateXML = new JButton("Generate XML", Utils.createImageIcon(Utils.HAMMER_ICON));
    generateXML.addActionListener(new ListenGenerateXML());
    buttonsHolder.add(generateXML);

    setOpaque(false);
    setLayout(new BorderLayout());
    add(optionPanel, BorderLayout.NORTH);
    add(buttonsHolder, BorderLayout.SOUTH);
  } // END: SimulationPanel
 private void initSoftWrapsSettingsProcessing() {
   ItemListener listener =
       new ItemListener() {
         @Override
         public void itemStateChanged(ItemEvent e) {
           updateSoftWrapSettingsRepresentation();
         }
       };
   myCbUseSoftWrapsAtEditor.addItemListener(listener);
   myCbUseCustomSoftWrapIndent.addItemListener(listener);
 }
Esempio n. 6
0
  @Override
  public JComponent config() {
    FormLayout layout =
        new FormLayout("left:pref, 0:grow", "p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, 0:grow");
    PanelBuilder builder = new PanelBuilder(layout);
    builder.setBorder(Borders.EMPTY_BORDER);
    builder.setOpaque(false);

    CellConstraints cc = new CellConstraints();

    JComponent cmp = builder.addSeparator("Audio settings", cc.xyw(2, 1, 1));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    noresample = new JCheckBox(Messages.getString("TrTab2.22"));
    noresample.setContentAreaFilled(false);
    noresample.setSelected(configuration.isAudioResample());
    noresample.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            configuration.setAudioResample(e.getStateChange() == ItemEvent.SELECTED);
          }
        });
    builder.add(noresample, cc.xy(2, 3));

    return builder.getPanel();
  }
  protected void createRemoveParamsPanel(GridBagConstraints gbConstraints, JPanel panel) {
    final JCheckBox[] removeParamsCb = new JCheckBox[myParametersToRemove.length];
    for (int i = 0; i < myParametersToRemove.length; i++) {
      PsiParameter parameter = myParametersToRemove[i];
      if (parameter == null) continue;
      final NonFocusableCheckBox cb =
          new NonFocusableCheckBox(
              RefactoringBundle.message("remove.parameter.0.no.longer.used", parameter.getName()));
      removeParamsCb[i] = cb;
      cb.setSelected(true);
      gbConstraints.gridy++;
      panel.add(cb, gbConstraints);
      final int i1 = i;
      cb.addChangeListener(
          new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
              myParametersToRemoveChecked[i1] = cb.isSelected();
            }
          });
      myParametersToRemoveChecked[i] = true;
    }

    updateControls(removeParamsCb);
    if (myCbReplaceAllOccurences != null) {
      myCbReplaceAllOccurences.addItemListener(
          new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
              updateControls(removeParamsCb);
            }
          });
    }
  }
Esempio n. 8
0
  private JPanel getClickableTagsPanel() {
    JPanel pnl = new JPanel();

    pnl.setLayout(new GridLayout(0, 3));

    ArrayList<Commontags> listTags = new ArrayList<>(mapAllTags.values());
    Collections.sort(listTags);

    for (final Commontags ctag : listTags) {
      JCheckBox cb = new JCheckBox(ctag.getText());

      cb.setForeground(GUITools.getColor(ctag.getColor()));
      cb.setFont(ctag.getType() == 0 ? SYSConst.ARIAL12 : SYSConst.ARIAL12BOLD);

      cb.setSelected(listSelectedTags.contains(ctag));

      cb.addItemListener(
          e -> {
            if (e.getStateChange() == ItemEvent.SELECTED) {
              listSelectedTags.add(ctag);
              add(createButton(ctag));
            } else {
              listSelectedTags.remove(ctag);
              mapButtons.remove(ctag);
            }
            notifyListeners(ctag);
          });

      pnl.add(cb);
    }
    return pnl;
  }
Esempio n. 9
0
 private JCheckBox createCheckBox(String s, boolean b, int y) {
   JCheckBox cb = new JCheckBox(s, b);
   cb.setFont(font);
   cb.setHorizontalAlignment(JCheckBox.LEFT);
   cb.addItemListener(this);
   Java2Demo.addToGridBag(this, cb, 0, y, 1, 1, 1.0, 1.0);
   return cb;
 }
 private void initVcsSettingsProcessing() {
   myShowLSTInGutterCheckBox.addItemListener(
       new ItemListener() {
         @Override
         public void itemStateChanged(ItemEvent e) {
           myShowWhitespacesModificationsInLSTGutterCheckBox.setEnabled(
               myShowLSTInGutterCheckBox.isSelected());
         }
       });
 }
Esempio n. 11
0
  @Override
  protected JComponent getComponent() {
    myReplaceAllCb.addItemListener(
        new ItemListener() {
          @Override
          public void itemStateChanged(ItemEvent e) {
            restartInplaceIntroduceTemplate();
          }
        });

    return myWholePanel;
  }
    public BooleanField(BooleanOption option) {
      super(option);

      checkbox = new JCheckBox();
      checkbox.setSelected(option.isDefault());
      checkbox.addItemListener(
          new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
              fireChangeEvent();
            }
          });
    }
 private void setUpShowInBrowserCheckBox() {
   openInBrowserCheckBox.addItemListener(
       new ItemListener() {
         @Override
         public void itemStateChanged(ItemEvent e) {
           boolean selected = openInBrowserCheckBox.isSelected();
           htmlChooseFile.setEnabled(selected);
           browserComboBox.setEnabled(selected);
           htmlFileLabel.setEnabled(selected);
           chooseBrowserLabel.setEnabled(selected);
         }
       });
 }
 @Override
 public Component getOptionsPanel() {
   JPanel panel = new JPanel(new GridLayout());
   final JCheckBox applyFileFilter = new JCheckBox("Show \"Program\" Folders/Files Only");
   applyFileFilter.addItemListener(
       new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
           _applyFileFilter = applyFileFilter.isSelected();
         }
       });
   panel.add(applyFileFilter);
   return panel;
 }
Esempio n. 15
0
  public int showDialog() {

    options = new OptionsPanel(6, 6);

    options.addComponent(autoScaleCheck);

    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    panel.add(fromLabel);
    panel.add(fromNumberField);
    panel.add(toLabel);
    panel.add(toNumberField);
    options.addComponent(panel);

    JPanel panel1 = new JPanel();
    panel1.setLayout(new FlowLayout());
    panel1.add(new JLabel("Width from:"));
    panel1.add(fromWidthField);
    panel1.add(new JLabel("to:"));
    panel1.add(toWidthField);
    options.addComponent(panel1);

    JOptionPane optionPane =
        new JOptionPane(
            options, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null, null);
    optionPane.setBorder(new EmptyBorder(12, 12, 12, 12));

    final JDialog dialog = optionPane.createDialog(frame, "Setup colour range");
    dialog.pack();

    autoScaleCheck.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            boolean enabled = !autoScaleCheck.isSelected();
            fromLabel.setEnabled(enabled);
            fromNumberField.setEnabled(enabled);
            toLabel.setEnabled(enabled);
            toNumberField.setEnabled(enabled);
          }
        });

    dialog.setVisible(true);

    int result = JOptionPane.CANCEL_OPTION;
    Integer value = (Integer) optionPane.getValue();
    if (value != null && value.intValue() != -1) {
      result = value.intValue();
    }

    return result;
  }
Esempio n. 16
0
  public WidthScaleDialog(
      final JFrame frame,
      boolean autoRange,
      double fromValue,
      double toValue,
      final double fromWidth,
      final double toWidth) {
    this.frame = frame;

    autoScaleCheck = new JCheckBox("Auto-scale range");
    autoScaleCheck.setSelected(autoRange);

    fromLabel = new JLabel("Range from:");
    fromNumberField = new RealNumberField();
    fromNumberField.setColumns(10);
    fromNumberField.setValue(fromValue);

    toLabel = new JLabel("to:");
    toNumberField = new RealNumberField();
    toNumberField.setColumns(10);
    toNumberField.setValue(toValue);

    fromLabel.setEnabled(false);
    fromNumberField.setEnabled(false);
    toLabel.setEnabled(false);
    toNumberField.setEnabled(false);

    fromWidthField = new RealNumberField();
    fromWidthField.setColumns(4);
    fromWidthField.setValue(fromWidth);
    toWidthField = new RealNumberField();
    toWidthField.setColumns(4);
    toWidthField.setValue(toWidth);

    autoScaleCheck.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            boolean enabled = !autoScaleCheck.isSelected();
            fromLabel.setEnabled(enabled);
            fromNumberField.setEnabled(enabled);
            toLabel.setEnabled(enabled);
            toNumberField.setEnabled(enabled);
          }
        });
  }
Esempio n. 17
0
  /** Add listeners to components. */
  private void addListeners() {
    dirBttn.addActionListener(this);
    backupBttn.addActionListener(this);
    runBttn.addActionListener(this);

    recursiveCheckBox.addItemListener(this);
    templateCh.addItemListener(this);

    dirTF.addActionListener(this);

    staticVersioningRadioButton.addItemListener(this);
    dynamicVersioningRadioButton.addItemListener(this);

    addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            quit();
          }
        });
  }
  @Override
  protected void init() {
    super.init();

    if (myTextSelected == Boolean.TRUE) {
      myRbSelectedText.setSelected(true);
    } else {
      if (myFile != null) {
        myRbFile.setSelected(true);
      } else {
        myRbDirectory.setSelected(true);
      }
    }

    myCbIncludeSubdirs.setSelected(true);
    // Loading previous state
    myCbOptimizeImports.setSelected(
        PropertiesComponent.getInstance()
            .getBoolean(LayoutCodeConstants.OPTIMIZE_IMPORTS_KEY, false));
    myCbArrangeEntries.setSelected(
        PropertiesComponent.getInstance()
            .getBoolean(LayoutCodeConstants.REARRANGE_ENTRIES_KEY, false));
    myCbOnlyVcsChangedRegions.setSelected(
        PropertiesComponent.getInstance()
            .getBoolean(LayoutCodeConstants.PROCESS_CHANGED_TEXT_KEY, false));

    ItemListener listener =
        new ItemListener() {
          @Override
          public void itemStateChanged(ItemEvent e) {
            updateState();
          }
        };
    myRbFile.addItemListener(listener);
    myRbSelectedText.addItemListener(listener);
    myRbDirectory.addItemListener(listener);
    myCbIncludeSubdirs.addItemListener(listener);

    updateState();
  }
Esempio n. 19
0
  private void setupCheckboxes(List<SearchEngine> searchEngines, JPanel parent) {

    final Map<JCheckBox, BooleanSetting> cBoxes = new HashMap<JCheckBox, BooleanSetting>();

    ItemListener listener =
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            if (areAll(false)) {
              ((JCheckBox) e.getItemSelectable()).setSelected(true);
            }

            if (resultPanel != null) {
              resultPanel.filterChanged(new SearchEngineFilter(engineCheckboxes), 0);
            }
          }
        };

    for (SearchEngine se : searchEngines) {
      JCheckBox cBox = new JCheckBox(se.getName());
      cBox.setSelected(se.isEnabled());
      cBox.setEnabled(se.isEnabled());

      if (!cBox.isEnabled()) {
        cBox.setToolTipText(
            se.getName()
                + " "
                + I18n.tr(
                    "has been disabled on your FrostWire Search Options. (Go to Tools > Options > Search to enable)"));
      }

      parent.add(cBox);

      cBoxes.put(cBox, se.getEnabledSetting());
      cBox.addItemListener(listener);

      engineCheckboxes.put(se, cBox);
    }
  }
  public ScalaApplicationSettingsForm(ScalaApplicationSettings settings) {
    mySettings = settings;

    myEnableCompileServer.addChangeListener(
        new ChangeListener() {
          public void stateChanged(ChangeEvent e) {
            updateCompilationServerSettingsPanel();
          }
        });

    initCompilerTypeCmb();
    initCompileOrderCmb();

    ProjectSdksModel model = new ProjectSdksModel();
    model.reset(null);

    myCompilationServerSdk = new JdkComboBox(model);
    myCompilationServerSdk.insertItemAt(new JdkComboBox.NoneJdkComboBoxItem(), 0);

    mySdkPanel.add(myCompilationServerSdk, BorderLayout.CENTER);
    mySdkPanel.setSize(mySdkPanel.getPreferredSize());

    myNote.setForeground(JBColor.GRAY);

    delaySpinner.setEnabled(showTypeInfoOnCheckBox.isSelected());
    showTypeInfoOnCheckBox.addItemListener(
        new ItemListener() {
          @Override
          public void itemStateChanged(ItemEvent e) {
            delaySpinner.setEnabled(showTypeInfoOnCheckBox.isSelected());
          }
        });
    delaySpinner.setValue(mySettings.SHOW_TYPE_TOOLTIP_DELAY);

    updateCompilationServerSettingsPanel();
  }
Esempio n. 21
0
  SwingTableDemo() {

    // Create a new JFrame container.
    JFrame jfrm = new JFrame("JTable Demo");

    // Specify FlowLayout for the layout manager.
    jfrm.setLayout(new FlowLayout());

    // Give the frame an initial size.
    jfrm.setSize(460, 180);

    // Terminate the program when the user closes the application.
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Create a table that displays order data.
    jtabOrders = new JTable(data, headings);

    // Wrap the table in a scroll pane.
    JScrollPane jscrlp = new JScrollPane(jtabOrders);

    // Set the scrollable viewport size.
    jtabOrders.setPreferredScrollableViewportSize(new Dimension(420, 62));

    // Create the radio buttons that determine
    // what type of selections are allowed.
    jrbRows = new JRadioButton("Select Rows", true);
    jrbColumns = new JRadioButton("Select Columns");
    jrbCells = new JRadioButton("Select Cells");

    // Add the radio buttons to a group.
    ButtonGroup bg = new ButtonGroup();
    bg.add(jrbRows);
    bg.add(jrbColumns);
    bg.add(jrbCells);

    // Radio button events are handled in common by the
    // actionPerformed() method implemented by TableDemo.
    jrbRows.addActionListener(this);
    jrbColumns.addActionListener(this);
    jrbCells.addActionListener(this);

    // Create the Single Selection Mode check box.
    // When checked, only single selections are allowed.
    jcbSingle = new JCheckBox("Single Selection Mode");

    // Add item listener for jcbSingle.
    jcbSingle.addItemListener(
        new ItemListener() {

          public void itemStateChanged(ItemEvent ie) {
            if (jcbSingle.isSelected())
              // Allow single selections.
              jtabOrders.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            else
              // Allow multiple selections.
              jtabOrders.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
          }
        });

    // Add the components to the content pane.
    jfrm.add(jscrlp);
    jfrm.add(jrbRows);
    jfrm.add(jrbColumns);
    jfrm.add(jrbCells);
    jfrm.add(jcbSingle);

    // Display the frame.
    jfrm.setVisible(true);
  }
Esempio n. 22
0
  /**
   * Creates dialog.
   *
   * @param aFrame parent frame.
   * @param aTitle dialog title.
   * @param aPublishingAvailable <code>TRUE</code> if publishing is available.
   * @param aPublishingLimit the number of guides the user can have published.
   * @param aPublishingLimitReached <code>TRUE</code> if the limit is reached.
   */
  public BasicGuideDialog(
      Frame aFrame,
      String aTitle,
      boolean aPublishingAvailable,
      int aPublishingLimit,
      boolean aPublishingLimitReached) {
    super(aFrame, aTitle);

    publishingAvailable = aPublishingAvailable;
    publishingLimit = aPublishingLimit;
    publishingLimitReached = aPublishingLimitReached;

    presentTitles = Collections.EMPTY_SET;
    model = new GuideIcons.ComboBoxModel();
    renderer = new IconListCellRenderer();
    readingListsModel = new ReadingListsTableModel();

    tblReadingLists = new JTable(readingListsModel);
    tblReadingLists.setDefaultRenderer(
        String.class, new ReadingListsTableCellRenderer(readingListsModel));
    UifUtilities.setTableColWidth(tblReadingLists, 2, 90);

    btnAddReadingList = new JButton(null, ResourceUtils.getIcon("add.icon"));
    btnAddReadingList.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            onAddReadingList();
          }
        });
    btnRemoveList = new JButton(null, ResourceUtils.getIcon("delete.icon"));
    btnRemoveList.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            onRemoveReadingList();
          }
        });

    // Publishing components
    chPublishingEnabled =
        ComponentsFactory.createCheckBox(Strings.message("guide.dialog.enable.publishing"));
    lbPublishingPublic = new JLabel(Strings.message("guide.dialog.public.visibility"));
    chPublishingPublic = new JCheckBox();
    lbPublishingTitle =
        ComponentsFactory.createLabel(Strings.message("guide.dialog.reading.list.title"));
    lbPublishingTags = ComponentsFactory.createLabel(Strings.message("guide.dialog.tags"));
    lbPublishingURL = new JLabel(Strings.message("guide.dialog.publicationurl"));
    lnkPublishingURL = new LinkLabel(Strings.message("guide.dialog.not.published.yet"));
    lbLastPublishingDate = new JLabel(Strings.message("guide.dialog.last.update.date"));
    tfLastPublishingDate = new JLabel(Strings.message("guide.dialog.never.updated"));
    tfPublishingTitle = new JTextField();
    lbPublishingTitle.setLabelFor(tfPublishingTitle);
    tfPublishingTags = new JTextField();
    lbPublishingTags.setLabelFor(tfPublishingTags);

    vhPublishingRating = new ValueHolder(1);
    sscPublishingRating =
        new StarsSelectionComponent(new BoundedRangeAdapter(vhPublishingRating, 0, 1, 5));
    lbPublishingRating = new JLabel(Strings.message("guide.dialog.rating"));

    btnCopyToClipboard = new JButton(Strings.message("guide.dialog.copy"));
    btnCopyToClipboard.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            CommonUtils.copyTextToClipboard(lnkPublishingURL.getText());
          }
        });

    onPublishingEnabled();
    chPublishingEnabled.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            onPublishingEnabled();
          }
        });

    chAllowNotifications =
        ComponentsFactory.createCheckBox(Strings.message("guide.dialog.allow.notifications"));
  }
  // constructor
  public Quiz8() {

    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    quiz = new JLabel("Quiz 8.1");
    quiz.setFont(new Font("Helvetica", Font.PLAIN, 25));
    // QUIZ QUESTIONS
    // -----------------------------------------------------------------------------------------------------------//

    question2 = new JLabel("What is Inheritance?");
    question2.setFont(new Font("Helvetica", Font.BOLD, 15));

    b1 = new JCheckBox("When a class receives aspects of another class.");
    b2 = new JCheckBox("When a Class dies and another gains its aspects. ");
    b3 = new JCheckBox("Passing down variables.");
    b4 = new JCheckBox("That thing at the place.");

    question3 = new JLabel("The parent and child class are also called: ");
    question3.setFont(new Font("Helvetica", Font.BOLD, 15));

    c1 = new JCheckBox("Base and subclass");
    c2 = new JCheckBox("A and B class");
    c3 = new JCheckBox("Origin and spawn class");
    c4 = new JCheckBox(" Master and Slave class");
    // italic.setBackground(Color.cyan);

    question4 = new JLabel("Which of these could be parent and child?");
    question4.setFont(new Font("Helvetica", Font.BOLD, 15));

    d1 = new JCheckBox("Map and Destination");
    d2 = new JCheckBox("Worker and Work ");
    d3 = new JCheckBox("Ring and Ding");
    d4 = new JCheckBox("Fish and Motorboat ");

    question5 =
        new JLabel(
            "What modifier keeps things under wraps yet allows it to be seen in Inheritance?");
    question5.setFont(new Font("Helvetica", Font.BOLD, 15));

    e1 = new JCheckBox("Protected");
    e2 = new JCheckBox("Secret");
    e3 = new JCheckBox("Background");
    e4 = new JCheckBox("Inherit");

    question6 = new JLabel("An abstract class");
    question6.setFont(new Font("Helvetica", Font.BOLD, 15));

    f1 = new JCheckBox("contains empty methods");
    f2 = new JCheckBox("Contains generic methods that can get filled out. ");
    f3 = new JCheckBox("Is made by crappy artists.");
    f4 = new JCheckBox("is hard to define.");

    question7 = new JLabel("Shadow Variables:");
    question7.setFont(new Font("Helvetica", Font.BOLD, 15));

    g1 = new JCheckBox("Are strongly advised against");
    g2 = new JCheckBox("Essential in Inheritance");
    g3 = new JCheckBox(" are variables with new values");
    g4 = new JCheckBox("Always protected.");

    //
    StyleListener listener6 = new StyleListener();
    b1.addItemListener(listener6);
    c1.addItemListener(listener6);
    d1.addItemListener(listener6);
    e1.addItemListener(listener6);
    f1.addItemListener(listener6);
    g1.addItemListener(listener6);

    submit8 = new JButton("Submit");
    submit8.addActionListener(new ButtonListener());

    add(quiz);
    add(question2);
    add(b1);
    add(b2);
    add(b3);
    add(b4);
    add(question3);
    add(c1);
    add(c2);
    add(c3);
    add(c4);
    add(question4);
    add(d1);
    add(d2);
    add(d3);
    add(d4);
    add(question5);
    add(e1);
    add(e2);
    add(e3);
    add(e4);
    add(question6);
    add(f1);
    add(f2);
    add(f3);
    add(f4);
    add(question7);
    add(g1);
    add(g2);
    add(g3);
    add(g4);
    add(submit8);
    setPreferredSize(new Dimension(800, 800));
    // setResizeable(false);
  }
Esempio n. 24
0
  public void show(List<Rule> rules) {
    if (original != null) config.restoreState(original);
    dialog = new JDialog(owner, true);
    dialog.setTitle(messages.getString("guiConfigWindowTitle"));

    Collections.sort(rules, new CategoryComparator());

    // close dialog when user presses Escape key:
    final KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    final ActionListener actionListener =
        new ActionListener() {
          @Override
          public void actionPerformed(@SuppressWarnings("unused") ActionEvent actionEvent) {
            dialog.setVisible(false);
          }
        };
    final JRootPane rootPane = dialog.getRootPane();
    rootPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

    // JPanel
    final JPanel checkBoxPanel = new JPanel();
    checkBoxPanel.setLayout(new GridBagLayout());
    GridBagConstraints cons = new GridBagConstraints();
    cons.anchor = GridBagConstraints.NORTHWEST;
    cons.gridx = 0;
    cons.weightx = 1.0;
    cons.weighty = 1.0;
    cons.fill = GridBagConstraints.BOTH;
    DefaultMutableTreeNode rootNode = createTree(rules);
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    treeModel.addTreeModelListener(
        new TreeModelListener() {

          @Override
          public void treeNodesChanged(TreeModelEvent e) {
            DefaultMutableTreeNode node =
                (DefaultMutableTreeNode) e.getTreePath().getLastPathComponent();
            int index = e.getChildIndices()[0];
            node = (DefaultMutableTreeNode) (node.getChildAt(index));
            if (node instanceof RuleNode) {
              RuleNode o = (RuleNode) node;
              if (o.getRule().isDefaultOff()) {
                if (o.isEnabled()) {
                  config.getEnabledRuleIds().add(o.getRule().getId());
                } else {
                  config.getEnabledRuleIds().remove(o.getRule().getId());
                }
              } else {
                if (o.isEnabled()) {
                  config.getDisabledRuleIds().remove(o.getRule().getId());
                } else {
                  config.getDisabledRuleIds().add(o.getRule().getId());
                }
              }
            }
            if (node instanceof CategoryNode) {
              CategoryNode o = (CategoryNode) node;
              if (o.isEnabled()) {
                config.getDisabledCategoryNames().remove(o.getCategory().getName());
              } else {
                config.getDisabledCategoryNames().add(o.getCategory().getName());
              }
            }
          }

          @Override
          public void treeNodesInserted(TreeModelEvent e) {}

          @Override
          public void treeNodesRemoved(TreeModelEvent e) {}

          @Override
          public void treeStructureChanged(TreeModelEvent e) {}
        });
    configTree = new JTree(treeModel);
    configTree.setRootVisible(false);
    configTree.setEditable(false);
    configTree.setCellRenderer(new CheckBoxTreeCellRenderer());
    TreeListener.install(configTree);
    checkBoxPanel.add(configTree, cons);

    MouseAdapter ma =
        new MouseAdapter() {
          private void handlePopupEvent(MouseEvent e) {
            final JTree tree = (JTree) e.getSource();

            TreePath path = tree.getPathForLocation(e.getX(), e.getY());
            if (path == null) {
              return;
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();

            TreePath[] paths = tree.getSelectionPaths();

            boolean isSelected = false;
            if (paths != null) {
              for (TreePath selectionPath : paths) {
                if (selectionPath.equals(path)) {
                  isSelected = true;
                }
              }
            }
            if (!isSelected) {
              tree.setSelectionPath(path);
            }
            if (node.isLeaf()) {
              JPopupMenu popup = new JPopupMenu();
              final JMenuItem aboutRuleMenuItem =
                  new JMenuItem(messages.getString("guiAboutRuleMenu"));
              aboutRuleMenuItem.addActionListener(
                  new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                      RuleNode node = (RuleNode) tree.getSelectionPath().getLastPathComponent();
                      Rule rule = node.getRule();
                      Language lang = config.getLanguage();
                      if (lang == null) {
                        lang = Language.getLanguageForLocale(Locale.getDefault());
                      }
                      Tools.showRuleInfoDialog(
                          tree,
                          messages.getString("guiAboutRuleTitle"),
                          rule.getDescription(),
                          rule,
                          messages,
                          lang.getShortNameWithCountryAndVariant());
                    }
                  });
              popup.add(aboutRuleMenuItem);
              popup.show(tree, e.getX(), e.getY());
            }
          }

          @Override
          public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
              handlePopupEvent(e);
            }
          }

          @Override
          public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
              handlePopupEvent(e);
            }
          }
        };
    configTree.addMouseListener(ma);
    final JPanel treeButtonPanel = new JPanel();
    cons = new GridBagConstraints();
    cons.gridx = 0;
    cons.gridy = 0;
    final JButton expandAllButton = new JButton(messages.getString("guiExpandAll"));
    treeButtonPanel.add(expandAllButton, cons);
    expandAllButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            TreeNode root = (TreeNode) configTree.getModel().getRoot();
            TreePath parent = new TreePath(root);
            for (Enumeration categ = root.children(); categ.hasMoreElements(); ) {
              TreeNode n = (TreeNode) categ.nextElement();
              TreePath child = parent.pathByAddingChild(n);
              configTree.expandPath(child);
            }
          }
        });

    cons.gridx = 1;
    cons.gridy = 0;
    final JButton collapseAllbutton = new JButton(messages.getString("guiCollapseAll"));
    treeButtonPanel.add(collapseAllbutton, cons);
    collapseAllbutton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            TreeNode root = (TreeNode) configTree.getModel().getRoot();
            TreePath parent = new TreePath(root);
            for (Enumeration categ = root.children(); categ.hasMoreElements(); ) {
              TreeNode n = (TreeNode) categ.nextElement();
              TreePath child = parent.pathByAddingChild(n);
              configTree.collapsePath(child);
            }
          }
        });

    final JPanel motherTonguePanel = new JPanel();
    motherTonguePanel.add(new JLabel(messages.getString("guiMotherTongue")), cons);
    motherTongueBox = new JComboBox(getPossibleMotherTongues());
    if (config.getMotherTongue() != null) {
      motherTongueBox.setSelectedItem(config.getMotherTongue().getTranslatedName(messages));
    }
    motherTongueBox.addItemListener(
        new ItemListener() {

          @Override
          public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
              Language motherTongue;
              if (motherTongueBox.getSelectedItem() instanceof String) {
                motherTongue =
                    getLanguageForLocalizedName(motherTongueBox.getSelectedItem().toString());
              } else {
                motherTongue = (Language) motherTongueBox.getSelectedItem();
              }
              config.setMotherTongue(motherTongue);
            }
          }
        });
    motherTonguePanel.add(motherTongueBox, cons);

    final JPanel portPanel = new JPanel();
    portPanel.setLayout(new GridBagLayout());
    // TODO: why is this now left-aligned?!?!
    cons = new GridBagConstraints();
    cons.insets = new Insets(0, 4, 0, 0);
    cons.gridx = 0;
    cons.gridy = 0;
    cons.anchor = GridBagConstraints.WEST;
    cons.fill = GridBagConstraints.NONE;
    cons.weightx = 0.0f;
    if (!insideOOo) {
      serverCheckbox = new JCheckBox(Tools.getLabel(messages.getString("guiRunOnPort")));
      serverCheckbox.setMnemonic(Tools.getMnemonic(messages.getString("guiRunOnPort")));
      serverCheckbox.setSelected(config.getRunServer());
      portPanel.add(serverCheckbox, cons);
      serverCheckbox.addActionListener(
          new ActionListener() {
            @Override
            public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
              serverPortField.setEnabled(serverCheckbox.isSelected());
              serverSettingsCheckbox.setEnabled(serverCheckbox.isSelected());
            }
          });
      serverCheckbox.addItemListener(
          new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
              config.setRunServer(serverCheckbox.isSelected());
            }
          });

      serverPortField = new JTextField(Integer.toString(config.getServerPort()));
      serverPortField.setEnabled(serverCheckbox.isSelected());
      serverSettingsCheckbox = new JCheckBox(Tools.getLabel(messages.getString("useGUIConfig")));
      // TODO: without this the box is just a few pixels small, but why??:
      serverPortField.setMinimumSize(new Dimension(100, 25));
      cons.gridx = 1;
      portPanel.add(serverPortField, cons);
      serverPortField
          .getDocument()
          .addDocumentListener(
              new DocumentListener() {

                @Override
                public void insertUpdate(DocumentEvent e) {
                  changedUpdate(e);
                }

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

                @Override
                public void changedUpdate(DocumentEvent e) {
                  try {
                    int serverPort = Integer.parseInt(serverPortField.getText());
                    if (serverPort > -1 && serverPort < 65536) {
                      serverPortField.setForeground(null);
                      config.setServerPort(serverPort);
                    } else {
                      serverPortField.setForeground(Color.RED);
                    }
                  } catch (NumberFormatException ex) {
                    serverPortField.setForeground(Color.RED);
                  }
                }
              });

      cons.gridx = 0;
      cons.gridy = 10;
      serverSettingsCheckbox.setMnemonic(Tools.getMnemonic(messages.getString("useGUIConfig")));
      serverSettingsCheckbox.setSelected(config.getUseGUIConfig());
      serverSettingsCheckbox.setEnabled(config.getRunServer());
      serverSettingsCheckbox.addItemListener(
          new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
              config.setUseGUIConfig(serverSettingsCheckbox.isSelected());
            }
          });
      portPanel.add(serverSettingsCheckbox, cons);
    }

    final JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridBagLayout());
    okButton = new JButton(Tools.getLabel(messages.getString("guiOKButton")));
    okButton.setMnemonic(Tools.getMnemonic(messages.getString("guiOKButton")));
    okButton.addActionListener(this);
    cancelButton = new JButton(Tools.getLabel(messages.getString("guiCancelButton")));
    cancelButton.setMnemonic(Tools.getMnemonic(messages.getString("guiCancelButton")));
    cancelButton.addActionListener(this);
    cons = new GridBagConstraints();
    cons.insets = new Insets(0, 4, 0, 0);
    buttonPanel.add(okButton, cons);
    buttonPanel.add(cancelButton, cons);

    final Container contentPane = dialog.getContentPane();
    contentPane.setLayout(new GridBagLayout());
    cons = new GridBagConstraints();
    cons.insets = new Insets(4, 4, 4, 4);
    cons.gridx = 0;
    cons.gridy = 0;
    cons.weightx = 10.0f;
    cons.weighty = 10.0f;
    cons.fill = GridBagConstraints.BOTH;
    contentPane.add(new JScrollPane(checkBoxPanel), cons);

    cons.gridx = 0;
    cons.gridy = 1;
    cons.weightx = 0.0f;
    cons.weighty = 0.0f;
    cons.fill = GridBagConstraints.NONE;
    cons.anchor = GridBagConstraints.LINE_END;
    contentPane.add(treeButtonPanel, cons);

    cons.gridx = 0;
    cons.gridy = 2;
    cons.weightx = 0.0f;
    cons.weighty = 0.0f;
    cons.fill = GridBagConstraints.NONE;
    cons.anchor = GridBagConstraints.WEST;
    contentPane.add(motherTonguePanel, cons);

    cons.gridx = 0;
    cons.gridy = 3;
    cons.weightx = 0.0f;
    cons.weighty = 0.0f;
    cons.fill = GridBagConstraints.NONE;
    cons.anchor = GridBagConstraints.WEST;
    contentPane.add(portPanel, cons);

    cons.gridx = 0;
    cons.gridy = 4;
    cons.weightx = 0.0f;
    cons.weighty = 0.0f;
    cons.fill = GridBagConstraints.NONE;
    cons.anchor = GridBagConstraints.EAST;
    contentPane.add(buttonPanel, cons);

    dialog.pack();
    dialog.setSize(500, 500);
    // center on screen:
    final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    final Dimension frameSize = dialog.getSize();
    dialog.setLocation(
        screenSize.width / 2 - frameSize.width / 2, screenSize.height / 2 - frameSize.height / 2);
    dialog.setLocationByPlatform(true);
    dialog.setVisible(true);
  }
  public MavenArchetypesStep(MavenModuleBuilder builder, @Nullable StepAdapter step) {
    myBuilder = builder;
    myStep = step;
    Disposer.register(this, myLoadingIcon);

    myArchetypesTree = new Tree();
    myArchetypesTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
    JScrollPane archetypesScrollPane = ScrollPaneFactory.createScrollPane(myArchetypesTree);

    myArchetypesPanel.add(archetypesScrollPane, "archetypes");

    JPanel loadingPanel = new JPanel(new GridBagLayout());
    JPanel bp = new JPanel(new BorderLayout(10, 10));
    bp.add(new JLabel("Loading archetype list..."), BorderLayout.NORTH);
    bp.add(myLoadingIcon, BorderLayout.CENTER);

    loadingPanel.add(bp, new GridBagConstraints());

    myArchetypesPanel.add(ScrollPaneFactory.createScrollPane(loadingPanel), "loading");
    ((CardLayout) myArchetypesPanel.getLayout()).show(myArchetypesPanel, "archetypes");

    myUseArchetypeCheckBox.addItemListener(
        new ItemListener() {
          @Override
          public void itemStateChanged(ItemEvent e) {
            updateComponents();
            archetypeMayBeChanged();
          }
        });

    myAddArchetypeButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            doAddArchetype();
          }
        });

    myArchetypesTree.setRootVisible(false);
    myArchetypesTree.setShowsRootHandles(true);
    myArchetypesTree.setCellRenderer(new MyRenderer());
    myArchetypesTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    myArchetypesTree
        .getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              public void valueChanged(TreeSelectionEvent e) {
                updateArchetypeDescription();
                archetypeMayBeChanged();
              }
            });

    new TreeSpeedSearch(
            myArchetypesTree,
            new Convertor<TreePath, String>() {
              public String convert(TreePath path) {
                MavenArchetype info =
                    getArchetypeInfoFromPathComponent(path.getLastPathComponent());
                return info.groupId + ":" + info.artifactId + ":" + info.version;
              }
            })
        .setComparator(new SpeedSearchComparator(false));

    myArchetypeDescriptionField.setEditable(false);
    myArchetypeDescriptionField.setBackground(UIUtil.getPanelBackground());

    requestUpdate();
    updateComponents();
  }
Esempio n. 26
0
  public CPLayersPalette(CPCommonController controller) {
    super(controller);

    title = "Layers";

    // Widgets creation

    Image icons = controller.loadImage("smallicons.png");

    addButton = new CPIconButton(icons, 16, 16, 0, 1);
    addButton.addController(this);
    addButton.setCPActionCommand(CPCommandId.AddLayer);

    removeButton = new CPIconButton(icons, 16, 16, 1, 1);
    removeButton.addController(this);
    removeButton.setCPActionCommand(CPCommandId.RemoveLayer);

    alphaSlider = new CPAlphaSlider();

    blendCombo = new JComboBox<String>(modeNames);
    blendCombo.addActionListener(this);

    lw = new CPLayerWidget();
    renameField = new CPRenameField();
    lw.add(renameField);
    scrollPane = new JScrollPane(lw);

    cbSampleAllLayers = new JCheckBox("Sample All Layers");
    cbSampleAllLayers.setSelected(controller.artwork.isSampleAllLayers());
    cbSampleAllLayers.addItemListener(this);

    cbLockAlpha = new JCheckBox("Lock Alpha");
    cbLockAlpha.setSelected(controller.artwork.isLockAlpha());
    cbLockAlpha.addItemListener(this);

    // Layout

    // Add/Remove Layer
    Box hb = Box.createHorizontalBox();
    hb.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    hb.add(addButton);
    hb.add(Box.createRigidArea(new Dimension(5, 0)));
    hb.add(removeButton);
    hb.add(Box.createHorizontalGlue());

    // blend mode
    blendCombo.setPreferredSize(new Dimension(100, 16));

    Box hb2 = Box.createHorizontalBox();
    hb2.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    hb2.add(blendCombo);
    hb2.add(Box.createHorizontalGlue());

    // layer opacity
    alphaSlider.setPreferredSize(new Dimension(100, 16));
    alphaSlider.setMaximumSize(new Dimension(100, 16));

    Box hb3 = Box.createHorizontalBox();
    hb3.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    hb3.add(alphaSlider);
    hb3.add(Box.createRigidArea(new Dimension(0, 16)));
    hb3.add(Box.createHorizontalGlue());

    Box hb4 = Box.createHorizontalBox();
    hb4.add(cbSampleAllLayers);
    hb4.add(Box.createHorizontalGlue());

    Box hb5 = Box.createHorizontalBox();
    hb5.add(cbLockAlpha);
    hb5.add(Box.createHorizontalGlue());

    Box vb = Box.createVerticalBox();
    vb.add(hb2);
    vb.add(hb3);
    vb.add(hb4);
    vb.add(hb5);

    setLayout(new BorderLayout());
    add(scrollPane, BorderLayout.CENTER);
    add(vb, BorderLayout.PAGE_START);
    add(hb, BorderLayout.PAGE_END);

    // Set initial values
    CPArtwork artwork = controller.getArtwork();
    alphaSlider.setValue(artwork.getActiveLayer().getAlpha());

    // add listeners

    addListener();
    // validate();
    // pack();
  }
Esempio n. 27
0
  public JComponent buildCommon() {
    String colSpec = FormLayoutUtil.getColSpec(COMMON_COL_SPEC, orientation);
    FormLayout layout = new FormLayout(colSpec, COMMON_ROW_SPEC);
    PanelBuilder builder = new PanelBuilder(layout);
    builder.setBorder(Borders.EMPTY_BORDER);
    builder.setOpaque(false);

    CellConstraints cc = new CellConstraints();

    maxbuffer = new JTextField("" + configuration.getMaxMemoryBufferSize());
    maxbuffer.addKeyListener(
        new KeyListener() {
          @Override
          public void keyPressed(KeyEvent e) {}

          @Override
          public void keyTyped(KeyEvent e) {}

          @Override
          public void keyReleased(KeyEvent e) {
            try {
              int ab = Integer.parseInt(maxbuffer.getText());
              configuration.setMaxMemoryBufferSize(ab);
            } catch (NumberFormatException nfe) {
              LOGGER.debug(
                  "Could not parse max memory buffer size from \"" + maxbuffer.getText() + "\"");
            }
          }
        });

    JComponent cmp =
        builder.addSeparator(
            Messages.getString("NetworkTab.5"),
            FormLayoutUtil.flip(cc.xyw(1, 1, 3), colSpec, orientation));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    builder.addLabel(
        Messages.getString("NetworkTab.6")
            .replaceAll("MAX_BUFFER_SIZE", configuration.getMaxMemoryBufferSizeStr()),
        FormLayoutUtil.flip(cc.xy(1, 3), colSpec, orientation));
    builder.add(maxbuffer, FormLayoutUtil.flip(cc.xy(3, 3), colSpec, orientation));

    String nCpusLabel =
        String.format(
            Messages.getString("NetworkTab.7"), Runtime.getRuntime().availableProcessors());
    builder.addLabel(nCpusLabel, FormLayoutUtil.flip(cc.xy(1, 5), colSpec, orientation));

    String[] guiCores = new String[MAX_CORES];
    for (int i = 0; i < MAX_CORES; i++) {
      guiCores[i] = Integer.toString(i + 1);
    }
    nbcores = new JComboBox(guiCores);
    nbcores.setEditable(false);
    int nbConfCores = configuration.getNumberOfCpuCores();
    if (nbConfCores > 0 && nbConfCores <= MAX_CORES) {
      nbcores.setSelectedItem(Integer.toString(nbConfCores));
    } else {
      nbcores.setSelectedIndex(0);
    }

    nbcores.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            configuration.setNumberOfCpuCores(Integer.parseInt(e.getItem().toString()));
          }
        });
    builder.add(nbcores, FormLayoutUtil.flip(cc.xy(3, 5), colSpec, orientation));

    chapter_interval = new JTextField("" + configuration.getChapterInterval());
    chapter_interval.setEnabled(configuration.isChapterSupport());
    chapter_interval.addKeyListener(
        new KeyListener() {
          @Override
          public void keyPressed(KeyEvent e) {}

          @Override
          public void keyTyped(KeyEvent e) {}

          @Override
          public void keyReleased(KeyEvent e) {
            try {
              int ab = Integer.parseInt(chapter_interval.getText());
              configuration.setChapterInterval(ab);
            } catch (NumberFormatException nfe) {
              LOGGER.debug(
                  "Could not parse chapter interval from \"" + chapter_interval.getText() + "\"");
            }
          }
        });

    chapter_support = new JCheckBox(Messages.getString("TrTab2.52"));
    chapter_support.setContentAreaFilled(false);
    chapter_support.setSelected(configuration.isChapterSupport());

    chapter_support.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            configuration.setChapterSupport((e.getStateChange() == ItemEvent.SELECTED));
            chapter_interval.setEnabled(configuration.isChapterSupport());
          }
        });

    builder.add(chapter_support, FormLayoutUtil.flip(cc.xy(1, 7), colSpec, orientation));

    builder.add(chapter_interval, FormLayoutUtil.flip(cc.xy(3, 7), colSpec, orientation));

    cmp =
        builder.addSeparator(
            Messages.getString("TrTab2.3"),
            FormLayoutUtil.flip(cc.xyw(1, 11, 3), colSpec, orientation));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    channels =
        new JComboBox(
            new Object[] {
              Messages.getString("TrTab2.55"),
              Messages.getString("TrTab2.56") /*, "8 channels 7.1" */
            }); // 7.1 not supported by Mplayer :\
    channels.setEditable(false);
    if (configuration.getAudioChannelCount() == 2) {
      channels.setSelectedIndex(0);
    } else {
      channels.setSelectedIndex(1);
    }
    channels.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            configuration.setAudioChannelCount(
                Integer.parseInt(e.getItem().toString().substring(0, 1)));
          }
        });

    builder.addLabel(
        Messages.getString("TrTab2.50"), FormLayoutUtil.flip(cc.xy(1, 13), colSpec, orientation));
    builder.add(channels, FormLayoutUtil.flip(cc.xy(3, 13), colSpec, orientation));

    forcePCM = new JCheckBox(Messages.getString("TrTab2.27"));
    forcePCM.setContentAreaFilled(false);
    if (configuration.isMencoderUsePcm()) {
      forcePCM.setSelected(true);
    }
    forcePCM.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            configuration.setMencoderUsePcm(e.getStateChange() == ItemEvent.SELECTED);
          }
        });

    builder.add(forcePCM, FormLayoutUtil.flip(cc.xyw(1, 15, 3), colSpec, orientation));

    ac3remux =
        new JCheckBox(
            Messages.getString("MEncoderVideo.32")
                + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
    ac3remux.setContentAreaFilled(false);
    if (configuration.isRemuxAC3()) {
      ac3remux.setSelected(true);
    }
    ac3remux.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            configuration.setRemuxAC3((e.getStateChange() == ItemEvent.SELECTED));
          }
        });

    builder.add(ac3remux, FormLayoutUtil.flip(cc.xyw(1, 17, 3), colSpec, orientation));

    forceDTSinPCM =
        new JCheckBox(
            Messages.getString("TrTab2.28")
                + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
    forceDTSinPCM.setContentAreaFilled(false);
    if (configuration.isDTSEmbedInPCM()) {
      forceDTSinPCM.setSelected(true);
    }
    forceDTSinPCM.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            configuration.setDTSEmbedInPCM(forceDTSinPCM.isSelected());
            if (configuration.isDTSEmbedInPCM()) {
              JOptionPane.showMessageDialog(
                  (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
                  Messages.getString("TrTab2.10"),
                  "Information",
                  JOptionPane.INFORMATION_MESSAGE);
            }
          }
        });

    builder.add(forceDTSinPCM, FormLayoutUtil.flip(cc.xyw(1, 19, 3), colSpec, orientation));

    abitrate = new JTextField("" + configuration.getAudioBitrate());
    abitrate.addKeyListener(
        new KeyListener() {
          @Override
          public void keyPressed(KeyEvent e) {}

          @Override
          public void keyTyped(KeyEvent e) {}

          @Override
          public void keyReleased(KeyEvent e) {
            try {
              int ab = Integer.parseInt(abitrate.getText());
              configuration.setAudioBitrate(ab);
            } catch (NumberFormatException nfe) {
              LOGGER.debug("Could not parse audio bitrate from \"" + abitrate.getText() + "\"");
            }
          }
        });

    builder.addLabel(
        Messages.getString("TrTab2.29"), FormLayoutUtil.flip(cc.xy(1, 21), colSpec, orientation));
    builder.add(abitrate, FormLayoutUtil.flip(cc.xy(3, 21), colSpec, orientation));

    mpeg2remux =
        new JCheckBox(
            Messages.getString("MEncoderVideo.39")
                + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
    mpeg2remux.setContentAreaFilled(false);
    if (configuration.isMencoderRemuxMPEG2()) {
      mpeg2remux.setSelected(true);
    }
    mpeg2remux.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            configuration.setMencoderRemuxMPEG2((e.getStateChange() == ItemEvent.SELECTED));
          }
        });

    builder.add(mpeg2remux, FormLayoutUtil.flip(cc.xyw(1, 23, 3), colSpec, orientation));

    cmp =
        builder.addSeparator(
            Messages.getString("TrTab2.4"),
            FormLayoutUtil.flip(cc.xyw(1, 25, 3), colSpec, orientation));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    builder.addLabel(
        Messages.getString("TrTab2.32"),
        FormLayoutUtil.flip(cc.xyw(1, 29, 3), colSpec, orientation));

    Object data[] =
        new Object[] {
          configuration.getMencoderMainSettings(), /* default */
          String.format(
              "keyint=5:vqscale=1:vqmin=2  /* %s */", Messages.getString("TrTab2.60")), /* great */
          String.format(
              "keyint=5:vqscale=1:vqmin=1  /* %s */",
              Messages.getString("TrTab2.61")), /* lossless */
          String.format(
              "keyint=5:vqscale=2:vqmin=3  /* %s */",
              Messages.getString("TrTab2.62")), /* good (wired) */
          String.format(
              "keyint=25:vqmax=5:vqmin=2  /* %s */",
              Messages.getString("TrTab2.63")), /* good (wireless) */
          String.format(
              "keyint=25:vqmax=7:vqmin=2  /* %s */",
              Messages.getString("TrTab2.64")), /* medium (wireless) */
          String.format(
              "keyint=25:vqmax=8:vqmin=3  /* %s */", Messages.getString("TrTab2.65")) /* low */
        };

    MyComboBoxModel cbm = new MyComboBoxModel(data);

    vq = new JComboBox(cbm);
    vq.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
              String s = (String) e.getItem();
              if (s.indexOf("/*") > -1) {
                s = s.substring(0, s.indexOf("/*")).trim();
              }
              configuration.setMencoderMainSettings(s);
            }
          }
        });
    vq.getEditor()
        .getEditorComponent()
        .addKeyListener(
            new KeyListener() {
              @Override
              public void keyPressed(KeyEvent e) {}

              @Override
              public void keyTyped(KeyEvent e) {}

              @Override
              public void keyReleased(KeyEvent e) {
                vq.getItemListeners()[0].itemStateChanged(
                    new ItemEvent(vq, 0, vq.getEditor().getItem(), ItemEvent.SELECTED));
              }
            });
    vq.setEditable(true);
    builder.add(vq, FormLayoutUtil.flip(cc.xyw(1, 31, 3), colSpec, orientation));

    String help1 = Messages.getString("TrTab2.39");
    help1 += Messages.getString("TrTab2.40");
    help1 += Messages.getString("TrTab2.41");
    help1 += Messages.getString("TrTab2.42");
    help1 += Messages.getString("TrTab2.43");
    help1 += Messages.getString("TrTab2.44");

    JTextArea decodeTips = new JTextArea(help1);
    decodeTips.setEditable(false);
    decodeTips.setBorder(BorderFactory.createEtchedBorder());
    decodeTips.setBackground(new Color(255, 255, 192));
    builder.add(decodeTips, FormLayoutUtil.flip(cc.xyw(1, 41, 3), colSpec, orientation));

    disableSubs = new JCheckBox(Messages.getString("TrTab2.51"));
    disableSubs.setContentAreaFilled(false);

    cmp =
        builder.addSeparator(
            Messages.getString("TrTab2.7"),
            FormLayoutUtil.flip(cc.xyw(1, 33, 3), colSpec, orientation));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    builder.add(disableSubs, FormLayoutUtil.flip(cc.xy(1, 35), colSpec, orientation));

    builder.addLabel(
        Messages.getString("TrTab2.8"), FormLayoutUtil.flip(cc.xy(1, 37), colSpec, orientation));

    notranscode = new JTextField(configuration.getNoTranscode());
    notranscode.addKeyListener(
        new KeyListener() {
          @Override
          public void keyPressed(KeyEvent e) {}

          @Override
          public void keyTyped(KeyEvent e) {}

          @Override
          public void keyReleased(KeyEvent e) {
            configuration.setNoTranscode(notranscode.getText());
          }
        });
    builder.add(notranscode, FormLayoutUtil.flip(cc.xy(3, 37), colSpec, orientation));

    builder.addLabel(
        Messages.getString("TrTab2.9"), FormLayoutUtil.flip(cc.xy(1, 39), colSpec, orientation));

    forcetranscode = new JTextField(configuration.getForceTranscode());
    forcetranscode.addKeyListener(
        new KeyListener() {
          @Override
          public void keyPressed(KeyEvent e) {}

          @Override
          public void keyTyped(KeyEvent e) {}

          @Override
          public void keyReleased(KeyEvent e) {
            configuration.setForceTranscode(forcetranscode.getText());
          }
        });
    builder.add(forcetranscode, FormLayoutUtil.flip(cc.xy(3, 39), colSpec, orientation));

    JPanel panel = builder.getPanel();

    // Apply the orientation to the panel and all components in it
    panel.applyComponentOrientation(orientation);

    return panel;
  }
Esempio n. 28
0
  /**
   * This method is used to display the window to interact with obix as well as colibri.
   *
   * @param chosenComponents The {@link ObixObject} which have been chosen in the previous windows.
   * @return The container which contains all elemtents that are used for interacting with obix as
   *     well as colibri.
   */
  private Container interactionWindow(List<ObixObject> chosenComponents) {
    Container pane = new Container();
    pane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridwidth = 10;
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(30, 20, 0, 0);

    c.gridy++;
    pane.add(registeredColibriChannelCheckBox, c);

    JLabel label = new JLabel("OBIX Components");
    Font headerF = new Font("Courier", Font.BOLD, 25);
    label.setFont(headerF);
    c.gridy++;
    pane.add(label, c);

    /*
       Print lobby Data
    */
    for (ObixObject o : chosenComponents) {
      if (connector.getColibriChannel().getRegistered()) {
        connector.getColibriChannel().send(ColibriMessage.createAddServiceMessage(o));
      }

      c.gridy++;
      c.insets = new Insets(30, 10, 0, 0);

      JLabel uriLabel = new JLabel(o.getObixUri());
      uriLabel.setFont(new Font("Courier", Font.ITALIC, 15));
      c.gridx = 0;
      c.gridwidth = 10;
      pane.add(uriLabel, c);

      c.gridwidth = 1;
      c.insets = new Insets(5, 10, 0, 0);

      final JTextField textField = new JTextField("NOT OBSERVED", 20);
      Font tempF = new Font("Courier", Font.PLAIN, 15);
      textField.setFont(tempF);
      c.gridy++;
      pane.add(textField, c);

      JLabel unitLabel = new JLabel();
      if (o.hasUnit()) {
        String unitString = o.getUnit().symbol().get();
        int unitCode = unitString.codePointAt(0);
        if (unitCode == 65533) {
          unitString = "\u2103";
        }
        unitLabel.setText(unitString);
      }
      c.gridx++;
      pane.add(unitLabel, c);

      final JButton getObixButton = new JButton("GET from OBIX");
      c.gridx++;
      pane.add(getObixButton, c);

      final JButton getColibriButton = new JButton("GET from Colibri");
      c.gridx++;
      pane.add(getColibriButton, c);

      final JCheckBox writableCheckBox = new JCheckBox("Writable");
      writableCheckBox.setSelected(o.getObj().isWritable());
      writableCheckBox.setEnabled(false);
      c.gridx++;
      pane.add(writableCheckBox, c);

      final JCheckBox observeObixCheckBox = new JCheckBox("observe Obix Data");
      observeObixCheckBox.setMargin(new Insets(0, 20, 0, 20));
      c.gridx++;
      pane.add(observeObixCheckBox, c);

      final JCheckBox observedByColibriCheckBox = new JCheckBox("Colibri observes Data");
      observedByColibriCheckBox.setEnabled(false);
      commandFactory.addCommand(
          () -> observedByColibriCheckBox.setSelected(o.getObservedByColibri()));
      c.gridx++;
      pane.add(observedByColibriCheckBox, c);

      final JCheckBox addServiceCheckbox = new JCheckBox("Service Added to Colibri");
      commandFactory.addCommand(() -> addServiceCheckbox.setSelected(o.getAddedAsService()));
      commandFactory.addCommand(
          () -> addServiceCheckbox.setEnabled(connector.getColibriChannel().getRegistered()));
      c.gridx++;
      pane.add(addServiceCheckbox, c);

      final JCheckBox observeColibriActionsCheckbox = new JCheckBox("Observe Colibri Actions");
      if (o.getObj().isWritable()) {
        commandFactory.addCommand(
            () -> observeColibriActionsCheckbox.setEnabled(o.getAddedAsService()));
        commandFactory.addCommand(
            () -> observeColibriActionsCheckbox.setSelected(o.getObservesColibriActions()));
      } else {
        observeColibriActionsCheckbox.setEnabled(false);
      }
      c.gridx++;
      pane.add(observeColibriActionsCheckbox, c);

      representationRows.add(
          new RepresentationRow(
              uriLabel,
              observeObixCheckBox,
              textField,
              o,
              writableCheckBox,
              getObixButton,
              getColibriButton,
              addServiceCheckbox,
              observedByColibriCheckBox,
              observeColibriActionsCheckbox));
      PutToObixTask putToObixTask =
          new PutToObixTask(o, connector.getColibriChannel(), connector.getObixChannel(), null);
      connector.getColibriChannel().addPutToObixTask(o.getServiceUri(), putToObixTask);
      ObixObservationUpdates observationUpdates =
          new ObixObservationUpdates(observeObixCheckBox, textField, o, connector);

      /**
       * Listener for the checkbox which indicates, if an {@link ObixObject] is observed by the obix connector.
       */
      observeObixCheckBox.addItemListener(
          new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
              ObixObject object = new ObixObject("", o.getObixChannelPort());
              for (RepresentationRow r : GuiUtility.this.getRepresentationRows()) {
                if (r.getObservedCheckBox().equals(observeObixCheckBox)) {
                  object = r.getObixObject();
                }
              }
              if (e.getStateChange() == ItemEvent.SELECTED) {
                obixChannel.observe(object);
                commandFactory.addCommand(
                    object.getObixUri() + "ObserveCommand", observationUpdates::run);
              } else {
                commandFactory.removeCommand(object.getObixUri() + "ObserveCommand");
                object.getRelation().proactiveCancel();
              }
            }
          });

      /**
       * Listener for the checkbox which indicates, if an {@link ObixObject] is writeable.
       */
      writableCheckBox.addItemListener(
          new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
              ObixObject object = new ObixObject("", o.getObixChannelPort());
              for (RepresentationRow r : GuiUtility.this.getRepresentationRows()) {
                if (r.getWritableCheckbox().equals(writableCheckBox)) {
                  object = r.getObixObject();
                }
              }

              if (e.getStateChange() == ItemEvent.SELECTED) {

              } else {
                object.getObj().setWritable(false);
              }
              object = obixChannel.put(object);
              writableCheckBox.setSelected(object.getObj().isWritable());
            }
          });

      /**
       * Listener for the checkbox which indicates, if an {@link ObixObject] is added as a service at colibri.
       */
      addServiceCheckbox.addItemListener(
          new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
              ObixObject object = new ObixObject("", o.getObixChannelPort());
              for (RepresentationRow r : GuiUtility.this.getRepresentationRows()) {
                if (r.getAddedAsServiceCheckBox().equals(addServiceCheckbox)) {
                  object = r.getObixObject();
                }
              }
              if (e.getStateChange() == ItemEvent.SELECTED) {
                if (!object.getAddedAsService()) {
                  connector
                      .getColibriChannel()
                      .send(ColibriMessage.createAddServiceMessage(object));
                }
              } else {
                if (object.getAddedAsService()) {
                  connector
                      .getColibriChannel()
                      .send(ColibriMessage.createRemoveServiceMessage(object));
                }
              }
            }
          });

      /**
       * Listener for the checkbox which indicates, if the connector observes the actions that the colibri
       * semantic core performs on an {@link ObixObject].
       */
      observeColibriActionsCheckbox.addItemListener(
          new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
              ObixObject object = new ObixObject("", o.getObixChannelPort());
              for (RepresentationRow r : GuiUtility.this.getRepresentationRows()) {
                if (r.getObserveColibriActionsCheckbox().equals(observeColibriActionsCheckbox)) {
                  object = r.getObixObject();
                }
              }
              if (e.getStateChange() == ItemEvent.SELECTED) {
                if (!object.getObservesColibriActions()) {
                  connector
                      .getColibriChannel()
                      .send(ColibriMessage.createObserveServiceMessage(object));
                }
              } else {
                if (object.getObservesColibriActions()) {
                  connector
                      .getColibriChannel()
                      .send(ColibriMessage.createDetachServiceMessage(object));
                }
              }
            }
          });

      /** GET Obix button listener */
      Action getObixAction =
          new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
              ObixObject object = new ObixObject("", o.getObixChannelPort());
              JTextField textF = null;
              for (RepresentationRow r : GuiUtility.this.getRepresentationRows()) {
                if (r.getGetObixButton().equals(getObixButton)) {
                  object = r.getObixObject();
                  textF = r.getValueTextField();
                }
              }
              textField.setText("");
              object = obixChannel.get(object.getObixUri());
              textF.setText(object.toString());
              if (o.getObservedByColibri()) {
                o.getPutMessageToColibriTask().execute(o);
              }
            }
          };
      getObixButton.addActionListener(getObixAction);

      /** GET Colibri button listener */
      Action getColibriAction =
          new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
              ObixObject object = new ObixObject("", o.getObixChannelPort());
              JTextField textF = null;
              for (RepresentationRow r : GuiUtility.this.getRepresentationRows()) {
                if (r.getGetColibriButton().equals(getColibriButton)) {
                  object = r.getObixObject();
                  textF = r.getValueTextField();
                }
              }
              connector.getColibriChannel().send(ColibriMessage.createGetMessage(object));
            }
          };
      getColibriButton.addActionListener(getColibriAction);

      /**
       * Listener for the textfield connected with an {@link ObixObject}, to send PUT messages to
       * obix on <Enter>.
       */
      textField.addKeyListener(
          new KeyListener() {
            public void keyTyped(KeyEvent e) {
              // intentionally empty
            }

            public void keyPressed(KeyEvent e) {
              // intentionally empty
            }

            public void keyReleased(KeyEvent e) {
              if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                ObixObject object = new ObixObject("", o.getObixChannelPort());
                for (RepresentationRow r : GuiUtility.this.getRepresentationRows()) {
                  if (r.getValueTextField().equals(textField)) {
                    object = r.getObixObject();
                  }
                }
                object.setValueParameter1(textField.getText());
                textField.setText("");
                object = obixChannel.put(object);
                textField.setText(object.toString());
              }
            }
          });
    }

    JTextArea receivedMessagesTextArea = new JTextArea("Received Messages");
    receivedMessagesTextArea.setLineWrap(true);
    receivedMessagesTextArea.setWrapStyleWord(true);
    c.gridy++;
    c.gridx = 0;
    c.insets = new Insets(50, 0, 0, 0);
    c.gridwidth = 10;
    pane.add(receivedMessagesTextArea, c);
    receivedMessagesTextArea.setEnabled(false);
    commandFactory.addCommand(
        () ->
            receivedMessagesTextArea.setText(
                connector.getColibriChannel().getLastMessageReceived()));

    c.gridy++;
    c.gridwidth = 1;

    JLabel sendMessageLabel = new JLabel("Send Message to Colibri Semantic Core:");
    pane.add(sendMessageLabel, c);

    c.gridy++;
    c.gridwidth = 10;
    JTextArea sendMessageArea = new JTextArea("");
    pane.add(sendMessageArea, c);

    c.gridy++;
    c.gridwidth = 2;
    JButton sendQueMessageButton = new JButton("Send Query Message");
    pane.add(sendQueMessageButton, c);
    c.gridx++;
    c.gridx++;
    c.gridwidth = 2;
    JButton sendUpdMessageButton = new JButton("Send Update Message");
    pane.add(sendUpdMessageButton, c);

    commandFactory.addCommand(
        () -> sendQueMessageButton.setEnabled(connector.getColibriChannel().getRegistered()));
    commandFactory.addCommand(
        () -> sendUpdMessageButton.setEnabled(connector.getColibriChannel().getRegistered()));

    /** QUE to Colibri button listener */
    Action sendQueMessageAction =
        new AbstractAction() {
          @Override
          public void actionPerformed(ActionEvent e) {
            connector
                .getColibriChannel()
                .send(
                    ColibriMessage.createQueryMessage(
                        sendMessageArea.getText(), new ArrayList<>()));
          }
        };
    sendQueMessageButton.addActionListener(sendQueMessageAction);

    /** UPD to Colibri button listener */
    Action sendUpdMessageAction =
        new AbstractAction() {
          @Override
          public void actionPerformed(ActionEvent e) {
            connector
                .getColibriChannel()
                .send(ColibriMessage.createUpdateMessage(sendMessageArea.getText()));
          }
        };
    sendUpdMessageButton.addActionListener(sendUpdMessageAction);
    return pane;
  }
  /** Initialize the contents of the frame. */
  private void initialize() {
    frmSignIn = new JFrame("Login");
    frmSignIn.setTitle("Sign in");
    frmSignIn.setResizable(false);
    frmSignIn.setBounds(100, 100, 450, 357);
    frmSignIn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmSignIn.setLocationRelativeTo(null);

    JLabel lblEmail = new JLabel("Email:");
    lblEmail.setBounds(73, 108, 56, 18);

    JLabel lblPassword = new JLabel("Password:"******"Show Password");
    chckbxShowPassword.setBounds(130, 176, 128, 23);
    frmSignIn.getContentPane().add(chckbxShowPassword);

    chckbxShowPassword.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
              passwordField.setEchoChar((char) 0);
            } else {
              passwordField.setEchoChar(a);
            }
          }
        });

    JButton btnNewButton = new JButton("Sign in");
    btnNewButton.setBounds(325, 106, 72, 62);
    btnNewButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            username = textField.getText();
            String password = String.valueOf(passwordField.getPassword()); // getText()
            // is
            // deprecated;
            // changed
            // to
            // getPassword()
            // password.toLowerCase();  Do we want case sensitive email?
            /*
             * SHA implementation to validate password
             */

            VaultController v = new VaultController();
            int result = 0;
            try {
              result = v.loginCheck(username, password);
            } catch (NoSuchAlgorithmException e1) {

              e1.printStackTrace();
            }
            if (result == 1) {
              failedattempt = 0;
              frmSignIn.dispose();

            } else {
              txtWarning.setText("The Email and/or Password is incorrect. Please try again.");
              failedattempt++;
            }
            // TODO migrate failcheck to Vault controller!
            if (failedattempt > 1 && failedattempt < 5) {
              try {
                VaultController.Send(
                    "sentineldatavault",
                    "SENTINELDATA",
                    username,
                    "Security Warning",
                    "Dear user,\n\nYou have multiple failed login attempts for your account.\n"
                        + "If it is not you, please change your password immediately.\n\n"
                        + "Sincerely,\nSentinel Data Vault Team");
              } catch (AddressException e1) {
                e1.printStackTrace();
              } catch (MessagingException e1) {
                e1.printStackTrace();
              }
            } else if (failedattempt == 5) {
              DatabaseManager d = new DatabaseManager("vault_database");
              User u = d.retrieveUserFromDatabase(username);
              d.deleteAllEntriesFromDatabase(u);
              d.deleteUserFromDatabase(u);
              try {
                JOptionPane.showMessageDialog(
                    null,
                    "Your account data has been deleted due to multiple failed login attempts");
                VaultController.Send(
                    "sentineldatavault",
                    "SENTINELDATA",
                    username,
                    "Security Warning",
                    "Dear user,\n\nWe have deleted your account.\n"
                        + "Have a nice day.\n\n"
                        + "Sincerely,\nSentinel Data Vault Team");
              } catch (AddressException e1) {
                e1.printStackTrace();
              } catch (MessagingException e1) {
                e1.printStackTrace();
              }
            }
          }
        });
    frmSignIn.getContentPane().setLayout(null);

    btnSignUp = new JButton("Create new account");
    btnSignUp.setToolTipText("Click here to create a new Sentinel Data Vault account!");
    btnSignUp.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            SignupView signup = new SignupView();
            signup.setVisible(true);
          }
        });
    btnSignUp.setBounds(57, 264, 158, 27);
    frmSignIn.getContentPane().add(btnSignUp);
    frmSignIn.getContentPane().add(btnNewButton);
    frmSignIn.getContentPane().add(lblPassword);
    frmSignIn.getContentPane().add(lblEmail);
    frmSignIn.getContentPane().add(textField);
    frmSignIn.getContentPane().add(passwordField);

    btnForgotPassword = new JButton("I forgot my password");
    btnForgotPassword.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            frmSignIn.setVisible(false);
            PasswordRecoveryView p = new PasswordRecoveryView(frmSignIn);
          }
        });
    btnForgotPassword.setToolTipText("Click here to reset your account password");
    btnForgotPassword.setBounds(227, 264, 170, 27);
    frmSignIn.getContentPane().add(btnForgotPassword);

    lblSentinelDataVault = new JLabel("Sentinel Data Vault");
    lblSentinelDataVault.setFont(new Font("Dialog", Font.PLAIN, 22));
    lblSentinelDataVault.setBounds(119, 33, 206, 27);
    frmSignIn.getContentPane().add(lblSentinelDataVault);

    txtWarning = new JTextField();
    txtWarning.setForeground(new Color(220, 20, 60));
    txtWarning.setBorder(null);
    txtWarning.setOpaque(false);
    txtWarning.setFocusable(false);
    txtWarning.setEditable(false);
    txtWarning.setFont(new Font("Tahoma", Font.ITALIC, 12));
    txtWarning.setBackground(SystemColor.window);
    txtWarning.setBounds(57, 196, 340, 26);
    frmSignIn.getContentPane().add(txtWarning);
    txtWarning.setColumns(10);

    frmSignIn
        .getContentPane()
        .setFocusTraversalPolicy(
            new FocusTraversalOnArray(new Component[] {textField, passwordField, btnNewButton}));
    frmSignIn.setFocusTraversalPolicy(
        new FocusTraversalOnArray(new Component[] {textField, passwordField, btnNewButton}));
  }
Esempio n. 30
0
  /**
   * This method represents the window in which the preferred obix components can be chosen.
   *
   * @return The container in which the preferred obix components can be chosen.
   */
  private Container chooseComponents() {
    Container pane = new Container();
    pane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridwidth = 1;
    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 1;
    c.weighty = 1;
    c.insets = new Insets(5, 5, 5, 5);

    registeredColibriChannelCheckBox = new JCheckBox("IS REGISTERD ON COLIBRI SEMANTIC CORE");
    commandFactory.addCommand(
        () ->
            registeredColibriChannelCheckBox.setSelected(
                connector.getColibriChannel().getRegistered()));
    Font regF = new Font("Courier", Font.BOLD, 40);
    registeredColibriChannelCheckBox.setFont(regF);

    /**
     * Listener for the checkbox which indicates, if the obix connector is registered at colibri.
     */
    registeredColibriChannelCheckBox.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
              if (!connector.getColibriChannel().getRegistered()) {
                connector.getColibriChannel().send(ColibriMessage.createRegisterMessage(connector));
              }
            } else {
              if (connector.getColibriChannel().getRegistered()) {
                connector
                    .getColibriChannel()
                    .send(ColibriMessage.createDeregisterMessage(connector));
              }
            }
          }
        });

    pane.add(registeredColibriChannelCheckBox, c);

    Font titelF = new Font("Courier", Font.BOLD, 30);
    title = new JLabel("Please choose the components you want to work with");
    title.setFont(titelF);

    c.gridy++;
    pane.add(title, c);

    JTextField searchTextField = new JTextField("Search for a component");
    c.weightx = 1;
    c.weighty = 1;
    c.gridx++;
    pane.add(searchTextField, c);

    c.weightx = 0.25;
    c.weighty = 0.25;
    c.gridwidth = 1;
    c.gridx++;
    JButton searchButton = new JButton("Search");
    pane.add(searchButton, c);

    JCheckBox markAllCheckbox = new JCheckBox("Mark all components");
    c.gridy++;
    c.gridy++;
    pane.add(markAllCheckbox, c);

    for (String s : lobby.getObservedObjectsLists().keySet()) {
      if (!s.equals("all")) {
        List<ObixObject> objects = lobby.getObservedObjectsLists().get(s);
        JLabel header = new JLabel(s);
        Font headerF = new Font("Courier", Font.BOLD, 25);
        header.setFont(headerF);
        c.gridx = 0;
        c.gridy++;
        pane.add(header, c);
        for (ObixObject o : objects) {
          JCheckBox chooseCheckBox = new JCheckBox(o.getObixUri());
          JPanel innerPanel = new JPanel();
          innerPanel.setLayout(new FlowLayout(0, 0, 0));
          innerPanel.add(chooseCheckBox);
          c.gridx = 0;
          c.gridwidth = 10;
          c.gridy++;
          pane.add(innerPanel, c);
          representationRows.add(new RepresentationRow(o, chooseCheckBox));
        }
      }
    }
    JButton acceptButton = new JButton("Accept");
    c.gridx = 0;
    c.gridy++;
    pane.add(acceptButton, c);

    /** Accept button listener */
    Action acceptAction =
        new AbstractAction() {
          @Override
          public void actionPerformed(ActionEvent e) {
            List<ObixObject> chosenObjects = Collections.synchronizedList(new ArrayList<>());
            ;
            for (RepresentationRow r : GuiUtility.this.getRepresentationRows()) {
              if (r.getChooseCheckbox().isSelected()) {
                chosenObjects.add(r.getObixObject());
              }
            }
            representationRows.clear();
            cards.removeAll();
            JScrollPane scrollPane = new JScrollPane(chooseParameters(chosenObjects));
            scrollPane.getVerticalScrollBar().setUnitIncrement(16);
            scrollPane.setBorder(new EmptyBorder(20, 20, 20, 20));
            cards.add(scrollPane);
            // Display the window.
            mainFrame.pack();
          }
        };
    acceptButton.addActionListener(acceptAction);

    /** Search function listener */
    Action searchAction =
        new AbstractAction() {
          @Override
          public void actionPerformed(ActionEvent e) {
            String searchText = searchTextField.getText();
            for (RepresentationRow r : GuiUtility.this.getRepresentationRows()) {
              if (r.getChooseCheckbox().getText().contains(searchText)) {
                r.getChooseCheckbox().setForeground(Color.blue);
              } else {
                r.getChooseCheckbox().setForeground(Color.black);
              }
              r.getChooseCheckbox().revalidate();
              r.getChooseCheckbox().repaint();
            }
          }
        };
    searchTextField.addActionListener(searchAction);
    searchButton.addActionListener(searchAction);

    /** Mark all components function listener */
    Action markAllAction =
        new AbstractAction() {
          @Override
          public void actionPerformed(ActionEvent e) {
            for (RepresentationRow r : GuiUtility.this.getRepresentationRows()) {
              r.getChooseCheckbox().setSelected(true);
            }
          }
        };
    markAllCheckbox.addActionListener(markAllAction);

    return pane;
  }